JpegoptimFilter.php 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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(array($this->jpegoptimBin));
  47. if ($this->stripAll) {
  48. $pb->add('--strip-all');
  49. }
  50. if ($this->max) {
  51. $pb->add('--max='.$this->max);
  52. }
  53. $pb->add($input = tempnam(sys_get_temp_dir(), 'assetic_jpegoptim'));
  54. file_put_contents($input, $asset->getContent());
  55. $proc = $pb->getProcess();
  56. $proc->run();
  57. if (false !== strpos($proc->getOutput(), 'ERROR')) {
  58. unlink($input);
  59. throw new \RuntimeException($proc->getOutput());
  60. }
  61. $asset->setContent(file_get_contents($input));
  62. unlink($input);
  63. }
  64. }