closure_compiler.class.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /**
  3. * Proxy for the closure compiler. Allows to minify javascript files.
  4. * This makes use of CURL and calls the closure service.
  5. *
  6. * @license see /license.txt
  7. * @author Laurent Opprecht <laurent@opprecht.info> for the Univesity of Geneva
  8. * @see http://closure-compiler.appspot.com/home
  9. * @see https://developers.google.com/closure/compiler/
  10. *
  11. */
  12. class ClosureCompiler
  13. {
  14. const PARAM_OUTPUT_FORMAT = 'output_format';
  15. const PARAM_OUTPUT_INFO = 'output_info';
  16. const PARAM_COMPILATION_LEVEL = 'compilation_level';
  17. const PARAM_JS_CODE = 'js_code';
  18. const LEVEL_SIMPLE = 'SIMPLE_OPTIMIZATIONS';
  19. const LEVEL_WHITESPACE = 'WHITESPACE_ONLY';
  20. const LEVEL_ADVANCED = 'ADVANCED_OPTIMIZATIONS';
  21. const OUTPUT_FORMAT_TEXT = 'text';
  22. const OUTPUT_INFO_CODE = 'compiled_code';
  23. /**
  24. * Url of the service
  25. *
  26. * @return string
  27. */
  28. public static function url()
  29. {
  30. return 'closure-compiler.appspot.com/compile';
  31. }
  32. /**
  33. * Post data the closure compiler service. By default it returns minimized code
  34. * with the simple option.
  35. *
  36. * @param string $code Javascript code to minimify
  37. * @param array $params parameters to pass to the service
  38. * @return string minimified code
  39. */
  40. public static function post($code, $params = array())
  41. {
  42. if (!isset($params[self::PARAM_OUTPUT_FORMAT]))
  43. {
  44. $params[self::PARAM_OUTPUT_FORMAT] = self::OUTPUT_FORMAT_TEXT;
  45. }
  46. if (!isset($params[self::PARAM_OUTPUT_INFO]))
  47. {
  48. $params[self::PARAM_OUTPUT_INFO] = self::OUTPUT_INFO_CODE;
  49. }
  50. if (!isset($params[self::PARAM_COMPILATION_LEVEL]))
  51. {
  52. $params[self::PARAM_JS_CODE] = $code;
  53. }
  54. $params[self::PARAM_COMPILATION_LEVEL] = self::LEVEL_SIMPLE;
  55. $fields = array();
  56. foreach ($params as $key => $value)
  57. {
  58. $fields[] = $key . '=' . urlencode($value);
  59. }
  60. $fields = implode('&', $fields);
  61. $headers = array("Content-type: application/x-www-form-urlencoded");
  62. $url = self::url();
  63. $ch = curl_init();
  64. curl_setopt($ch, CURLOPT_URL, $url);
  65. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  66. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  67. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  68. curl_setopt($ch, CURLOPT_POST, true);
  69. curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
  70. //curl_setopt($ch, CURLOPT_HEADER, false);
  71. //curl_setopt($ch, CURLOPT_VERBOSE, true);
  72. $content = curl_exec($ch);
  73. $error = curl_error($ch);
  74. $info = curl_getinfo($ch);
  75. curl_close($ch);
  76. return $content;
  77. }
  78. }