1 | <?php |
---|
2 | |
---|
3 | /* |
---|
4 | * This file is part of the Assetic package, an OpenSky project. |
---|
5 | * |
---|
6 | * (c) 2010-2012 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 | |
---|
12 | namespace Assetic\Filter; |
---|
13 | |
---|
14 | use Assetic\Asset\AssetInterface; |
---|
15 | use Assetic\Exception\FilterException; |
---|
16 | use Symfony\Component\Process\ProcessBuilder; |
---|
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 | */ |
---|
24 | class JpegoptimFilter implements FilterInterface |
---|
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 = new ProcessBuilder(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 = tempnam(sys_get_temp_dir(), 'assetic_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 | } |
---|