JpegoptimFilter.php 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /*
  3. * This file is part of the Assetic package, an OpenSky project.
  4. *
  5. * (c) 2010-2011 OpenSky Project Inc
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Assetic\Filter;
  11. use Assetic\Asset\AssetInterface;
  12. use Assetic\Util\ProcessBuilder;
  13. /**
  14. * Runs assets through Jpegoptim.
  15. *
  16. * @link http://www.kokkonen.net/tjko/projects.html
  17. * @author Kris Wallsmith <kris.wallsmith@gmail.com>
  18. */
  19. class JpegoptimFilter implements FilterInterface
  20. {
  21. private $jpegoptimBin;
  22. private $stripAll;
  23. private $max;
  24. /**
  25. * Constructor.
  26. *
  27. * @param string $jpegoptimBin Path to the jpegoptim binary
  28. */
  29. public function __construct($jpegoptimBin = '/usr/bin/jpegoptim')
  30. {
  31. $this->jpegoptimBin = $jpegoptimBin;
  32. }
  33. public function setStripAll($stripAll)
  34. {
  35. $this->stripAll = $stripAll;
  36. }
  37. public function setMax($max)
  38. {
  39. $this->max = $max;
  40. }
  41. public function filterLoad(AssetInterface $asset)
  42. {
  43. }
  44. public function filterDump(AssetInterface $asset)
  45. {
  46. $pb = new ProcessBuilder();
  47. $pb
  48. ->inheritEnvironmentVariables()
  49. ->add($this->jpegoptimBin)
  50. ;
  51. if ($this->stripAll) {
  52. $pb->add('--strip-all');
  53. }
  54. if ($this->max) {
  55. $pb->add('--max='.$this->max);
  56. }
  57. $pb->add($input = tempnam(sys_get_temp_dir(), 'assetic_jpegoptim'));
  58. file_put_contents($input, $asset->getContent());
  59. $proc = $pb->getProcess();
  60. $proc->run();
  61. if (false !== strpos($proc->getOutput(), 'ERROR')) {
  62. unlink($input);
  63. throw new \RuntimeException($proc->getOutput());
  64. }
  65. $asset->setContent(file_get_contents($input));
  66. unlink($input);
  67. }
  68. }