FRED™  3.0
FRED™: Framework for Rapid and Easy Development
Script.php
Go to the documentation of this file.
1 <?php
2 
4 
5 class Script extends \Rsi\Fred\Minify\Handler{
6 
7  protected $_java = null;
8  protected $_jar = null;
9  protected $_url = 'https://closure-compiler.appspot.com/compile?compilation_level=SIMPLE_OPTIMIZATIONS&output_format=json&warning_level=verbose&output_info=compiled_code&output_info=errors&output_info=warnings';
10  protected $_ignore = []; //!< Regex's for compiler messages to ignore
11 
12  protected function local($script,$filename = null){
13  if(!$this->_java || !$this->_jar) return false;
14  $source = \Rsi\File::tempFile('js',$script);
15  $target = \Rsi\File::tempFile('js');
16  exec("{$this->_java} -jar {$this->_jar} --js $source --js_output_file $target");
17  $result = file_get_contents($target);
18  unlink($source);
19  unlink($target);
20  return $result;
21  }
22 
23  protected function service($script,$filename = null){
24  $ch = curl_init($this->_url);
25  curl_setopt($ch,CURLOPT_POSTFIELDS,'js_code=' . urlencode($script));
26  curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
27  $response = curl_exec($ch);
28  curl_close($ch);
29  if($response){
30  if($data = json_decode($response)){
31  foreach(['error' => \Rsi\Fred\Log::ERROR,'warning' => \Rsi\Fred\Log::NOTICE] as $key => $prio)
32  if(property_exists($data,$property = $key . 's')) foreach($data->$property as $message){
33  foreach($this->_ignore as $ignore) if(preg_match($ignore,$message->$key)) continue 2;
34  $this->_minify->log->add($prio,"Script $key: {$message->$key}",$filename,$message->lineno,(array)$message);
35  }
36  return $data->compiledCode;
37  }
38  else $this->_minify->log->error('Invalid response',__FILE__,__LINE__,['response' => $response,'error' => json_last_error_msg()]);
39  }
40  else $this->_minify->log->error('No response',__FILE__,__LINE__,['url' => $this->_url]);
41  return false;
42  }
43 
44  public function source($source,$filename = null){
45  try{
46  return ($this->local($source,$filename) ?: $this->service($source,$filename)) ?: $source;
47  }
48  catch(\Exception $e){
49  $this->_minify->log->error('Error while minimizing script: ' . $e->getMessage(),__FILE__,__LINE__);
50  return $source;
51  }
52  }
53 
54 }
service($script, $filename=null)
Definition: Script.php:23
const NOTICE
Normal, but significant, condition.
Definition: Log.php:13
const ERROR
Error conditions.
Definition: Log.php:11
local($script, $filename=null)
Definition: Script.php:12
Framework for Rapid and Easy Development.
Definition: Fred.php:18
$_ignore
Regex&#39;s for compiler messages to ignore.
Definition: Script.php:10
source($source, $filename=null)
Definition: Script.php:44