CompilerJarFilter.php 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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\GoogleClosure;
  11. use Assetic\Asset\AssetInterface;
  12. use Assetic\Util\ProcessBuilder;
  13. /**
  14. * Filter for the Google Closure Compiler JAR.
  15. *
  16. * @author Kris Wallsmith <kris.wallsmith@gmail.com>
  17. */
  18. class CompilerJarFilter extends BaseCompilerFilter
  19. {
  20. private $jarPath;
  21. private $javaPath;
  22. public function __construct($jarPath, $javaPath = '/usr/bin/java')
  23. {
  24. $this->jarPath = $jarPath;
  25. $this->javaPath = $javaPath;
  26. }
  27. public function filterDump(AssetInterface $asset)
  28. {
  29. $cleanup = array();
  30. $pb = new ProcessBuilder(array(
  31. $this->javaPath,
  32. '-jar',
  33. $this->jarPath,
  34. ));
  35. if (null !== $this->compilationLevel) {
  36. $pb->add('--compilation_level')->add($this->compilationLevel);
  37. }
  38. if (null !== $this->jsExterns) {
  39. $cleanup[] = $externs = tempnam(sys_get_temp_dir(), 'assetic_google_closure_compiler');
  40. file_put_contents($externs, $this->jsExterns);
  41. $pb->add('--externs')->add($externs);
  42. }
  43. if (null !== $this->externsUrl) {
  44. $cleanup[] = $externs = tempnam(sys_get_temp_dir(), 'assetic_google_closure_compiler');
  45. file_put_contents($externs, file_get_contents($this->externsUrl));
  46. $pb->add('--externs')->add($externs);
  47. }
  48. if (null !== $this->excludeDefaultExterns) {
  49. $pb->add('--use_only_custom_externs');
  50. }
  51. if (null !== $this->formatting) {
  52. $pb->add('--formatting')->add($this->formatting);
  53. }
  54. if (null !== $this->useClosureLibrary) {
  55. $pb->add('--manage_closure_dependencies');
  56. }
  57. if (null !== $this->warningLevel) {
  58. $pb->add('--warning_level')->add($this->warningLevel);
  59. }
  60. $pb->add('--js')->add($cleanup[] = $input = tempnam(sys_get_temp_dir(), 'assetic_google_closure_compiler'));
  61. file_put_contents($input, $asset->getContent());
  62. $proc = $pb->getProcess();
  63. $code = $proc->run();
  64. array_map('unlink', $cleanup);
  65. if (0 < $code) {
  66. throw new \RuntimeException($proc->getErrorOutput());
  67. }
  68. $asset->setContent($proc->getOutput());
  69. }
  70. }