1<?php
2
3/*
4 * This file is part of the Assetic package, an OpenSky project.
5 *
6 * (c) 2010-2014 OpenSky Project Inc
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Assetic\Filter;
13
14use Assetic\Asset\AssetInterface;
15use Assetic\Exception\FilterException;
16use Assetic\Util\FilesystemUtils;
17
18/**
19 * Runs assets through OptiPNG.
20 *
21 * @link   http://optipng.sourceforge.net/
22 * @author Kris Wallsmith <kris.wallsmith@gmail.com>
23 */
24class OptiPngFilter extends BaseProcessFilter
25{
26    private $optipngBin;
27    private $level;
28
29    /**
30     * Constructor.
31     *
32     * @param string $optipngBin Path to the optipng binary
33     */
34    public function __construct($optipngBin = '/usr/bin/optipng')
35    {
36        $this->optipngBin = $optipngBin;
37    }
38
39    public function setLevel($level)
40    {
41        $this->level = $level;
42    }
43
44    public function filterLoad(AssetInterface $asset)
45    {
46    }
47
48    public function filterDump(AssetInterface $asset)
49    {
50        $pb = $this->createProcessBuilder(array($this->optipngBin));
51
52        if (null !== $this->level) {
53            $pb->add('-o')->add($this->level);
54        }
55
56        $pb->add('-out')->add($output = FilesystemUtils::createTemporaryFile('optipng_out'));
57        unlink($output);
58
59        $pb->add($input = FilesystemUtils::createTemporaryFile('optinpg_in'));
60        file_put_contents($input, $asset->getContent());
61
62        $proc = $pb->getProcess();
63        $code = $proc->run();
64
65        if (0 !== $code) {
66            unlink($input);
67            throw FilterException::fromProcess($proc)->setInput($asset->getContent());
68        }
69
70        $asset->setContent(file_get_contents($output));
71
72        unlink($input);
73        unlink($output);
74    }
75}
76