CompilerApiFilter.php 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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\GoogleClosure;
  11. use Assetic\Asset\AssetInterface;
  12. /**
  13. * Filter for the Google Closure Compiler API.
  14. *
  15. * @author Kris Wallsmith <kris.wallsmith@gmail.com>
  16. */
  17. class CompilerApiFilter extends BaseCompilerFilter
  18. {
  19. public function filterDump(AssetInterface $asset)
  20. {
  21. $query = array(
  22. 'js_code' => $asset->getContent(),
  23. 'output_format' => 'json',
  24. 'output_info' => 'compiled_code',
  25. );
  26. if (null !== $this->compilationLevel) {
  27. $query['compilation_level'] = $this->compilationLevel;
  28. }
  29. if (null !== $this->jsExterns) {
  30. $query['js_externs'] = $this->jsExterns;
  31. }
  32. if (null !== $this->externsUrl) {
  33. $query['externs_url'] = $this->externsUrl;
  34. }
  35. if (null !== $this->excludeDefaultExterns) {
  36. $query['exclude_default_externs'] = $this->excludeDefaultExterns ? 'true' : 'false';
  37. }
  38. if (null !== $this->formatting) {
  39. $query['formatting'] = $this->formatting;
  40. }
  41. if (null !== $this->useClosureLibrary) {
  42. $query['use_closure_library'] = $this->useClosureLibrary ? 'true' : 'false';
  43. }
  44. if (null !== $this->warningLevel) {
  45. $query['warning_level'] = $this->warningLevel;
  46. }
  47. $context = stream_context_create(array('http' => array(
  48. 'method' => 'POST',
  49. 'header' => 'Content-Type: application/x-www-form-urlencoded',
  50. 'content' => http_build_query($query),
  51. )));
  52. $response = file_get_contents('http://closure-compiler.appspot.com/compile', false, $context);
  53. $data = json_decode($response);
  54. if (isset($data->serverErrors) && 0 < count($data->serverErrors)) {
  55. // @codeCoverageIgnoreStart
  56. throw new \RuntimeException(sprintf('The Google Closure Compiler API threw some server errors: '.print_r($data->serverErrors, true)));
  57. // @codeCoverageIgnoreEnd
  58. }
  59. if (isset($data->errors) && 0 < count($data->errors)) {
  60. // @codeCoverageIgnoreStart
  61. throw new \RuntimeException(sprintf('The Google Closure Compiler API threw some errors: '.print_r($data->errors, true)));
  62. // @codeCoverageIgnoreEnd
  63. }
  64. $asset->setContent($data->compiledCode);
  65. }
  66. }