JpegtranFilter.php 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 jpegtran.
  15. *
  16. * @author Kris Wallsmith <kris.wallsmith@gmail.com>
  17. */
  18. class JpegtranFilter implements FilterInterface
  19. {
  20. const COPY_NONE = 'none';
  21. const COPY_COMMENTS = 'comments';
  22. const COPY_ALL = 'all';
  23. private $jpegtranBin;
  24. private $optimize;
  25. private $copy;
  26. private $progressive;
  27. private $restart;
  28. /**
  29. * Constructor.
  30. *
  31. * @param string $jpegtranBin Path to the jpegtran binary
  32. */
  33. public function __construct($jpegtranBin = '/usr/bin/jpegtran')
  34. {
  35. $this->jpegtranBin = $jpegtranBin;
  36. }
  37. public function setOptimize($optimize)
  38. {
  39. $this->optimize = $optimize;
  40. }
  41. public function setCopy($copy)
  42. {
  43. $this->copy = $copy;
  44. }
  45. public function setProgressive($progressive)
  46. {
  47. $this->progressive = $progressive;
  48. }
  49. public function setRestart($restart)
  50. {
  51. $this->restart = $restart;
  52. }
  53. public function filterLoad(AssetInterface $asset)
  54. {
  55. }
  56. public function filterDump(AssetInterface $asset)
  57. {
  58. $pb = new ProcessBuilder(array($this->jpegtranBin));
  59. if ($this->optimize) {
  60. $pb->add('-optimize');
  61. }
  62. if ($this->copy) {
  63. $pb->add('-copy')->add($this->copy);
  64. }
  65. if ($this->progressive) {
  66. $pb->add('-progressive');
  67. }
  68. if (null !== $this->restart) {
  69. $pb->add('-restart')->add($this->restart);
  70. }
  71. $pb->add($input = tempnam(sys_get_temp_dir(), 'assetic_jpegtran'));
  72. file_put_contents($input, $asset->getContent());
  73. $proc = $pb->getProcess();
  74. $code = $proc->run();
  75. unlink($input);
  76. if (0 < $code) {
  77. throw new \RuntimeException($proc->getErrorOutput());
  78. }
  79. $asset->setContent($proc->getOutput());
  80. }
  81. }