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 Jpegoptim.
20 *
21 * @link   http://www.kokkonen.net/tjko/projects.html
22 * @author Kris Wallsmith <kris.wallsmith@gmail.com>
23 */
24class JpegoptimFilter extends BaseProcessFilter
25{
26    private $jpegoptimBin;
27    private $stripAll;
28    private $max;
29
30    /**
31     * Constructor.
32     *
33     * @param string $jpegoptimBin Path to the jpegoptim binary
34     */
35    public function __construct($jpegoptimBin = '/usr/bin/jpegoptim')
36    {
37        $this->jpegoptimBin = $jpegoptimBin;
38    }
39
40    public function setStripAll($stripAll)
41    {
42        $this->stripAll = $stripAll;
43    }
44
45    public function setMax($max)
46    {
47        $this->max = $max;
48    }
49
50    public function filterLoad(AssetInterface $asset)
51    {
52    }
53
54    public function filterDump(AssetInterface $asset)
55    {
56        $pb = $this->createProcessBuilder(array($this->jpegoptimBin));
57
58        if ($this->stripAll) {
59            $pb->add('--strip-all');
60        }
61
62        if ($this->max) {
63            $pb->add('--max='.$this->max);
64        }
65
66        $pb->add($input = FilesystemUtils::createTemporaryFile('jpegoptim'));
67        file_put_contents($input, $asset->getContent());
68
69        $proc = $pb->getProcess();
70        $proc->run();
71
72        if (false !== strpos($proc->getOutput(), 'ERROR')) {
73            unlink($input);
74            throw FilterException::fromProcess($proc)->setInput($asset->getContent());
75        }
76
77        $asset->setContent(file_get_contents($input));
78
79        unlink($input);
80    }
81}
82