OptiPngFilter.php 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /*
  3. * This file is part of the Assetic package, an OpenSky project.
  4. *
  5. * (c) 2010-2012 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 OptiPNG.
  15. *
  16. * @link http://optipng.sourceforge.net/
  17. * @author Kris Wallsmith <kris.wallsmith@gmail.com>
  18. */
  19. class OptiPngFilter implements FilterInterface
  20. {
  21. private $optipngBin;
  22. private $level;
  23. /**
  24. * Constructor.
  25. *
  26. * @param string $optipngBin Path to the optipng binary
  27. */
  28. public function __construct($optipngBin = '/usr/bin/optipng')
  29. {
  30. $this->optipngBin = $optipngBin;
  31. }
  32. public function setLevel($level)
  33. {
  34. $this->level = $level;
  35. }
  36. public function filterLoad(AssetInterface $asset)
  37. {
  38. }
  39. public function filterDump(AssetInterface $asset)
  40. {
  41. $pb = new ProcessBuilder(array($this->optipngBin));
  42. if (null !== $this->level) {
  43. $pb->add('-o')->add($this->level);
  44. }
  45. $pb->add('-out')->add($output = tempnam(sys_get_temp_dir(), 'assetic_optipng'));
  46. unlink($output);
  47. $pb->add($input = tempnam(sys_get_temp_dir(), 'assetic_optipng'));
  48. file_put_contents($input, $asset->getContent());
  49. $proc = $pb->getProcess();
  50. $code = $proc->run();
  51. if (0 < $code) {
  52. unlink($input);
  53. throw new \RuntimeException($proc->getErrorOutput());
  54. }
  55. $asset->setContent(file_get_contents($output));
  56. unlink($input);
  57. unlink($output);
  58. }
  59. }