| 1 |
<?php |
| 2 |
namespace JmesPath; |
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
class CompilerRuntime |
| 16 |
{ |
| 17 |
const CACHE_VERSION = 4; |
| 18 |
|
| 19 |
private $parser; |
| 20 |
private $compiler; |
| 21 |
private $cacheDir; |
| 22 |
private $interpreter; |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
public function __construct($dir = null, ?Parser $parser = null) |
| 30 |
{ |
| 31 |
$this->parser = $parser ?: new Parser(); |
| 32 |
$this->compiler = new TreeCompiler(); |
| 33 |
$dir = $dir ?: sys_get_temp_dir(); |
| 34 |
|
| 35 |
if (!is_dir($dir) && !mkdir($dir, 0755, true)) { |
| 36 |
throw new \RuntimeException("Unable to create cache directory: $dir"); |
| 37 |
} |
| 38 |
|
| 39 |
$this->cacheDir = realpath($dir); |
| 40 |
$this->interpreter = new TreeInterpreter(); |
| 41 |
} |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
public function __invoke($expression, $data) |
| 56 |
{ |
| 57 |
$functionName = self::functionName($expression); |
| 58 |
|
| 59 |
if (!function_exists($functionName)) { |
| 60 |
$filename = "{$this->cacheDir}/{$functionName}.php"; |
| 61 |
if (!file_exists($filename)) { |
| 62 |
$this->compile($filename, $expression, $functionName); |
| 63 |
} |
| 64 |
require $filename; |
| 65 |
} |
| 66 |
|
| 67 |
return $functionName($this->interpreter, $data); |
| 68 |
} |
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
public static function functionName($expression) |
| 74 |
{ |
| 75 |
return 'jmespath_' . md5( |
| 76 |
'jmespath:' . PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION |
| 77 |
. ':' . self::CACHE_VERSION . ':' . $expression |
| 78 |
); |
| 79 |
} |
| 80 |
|
| 81 |
|
| 82 |
public function getCacheDir() |
| 83 |
{ |
| 84 |
return $this->cacheDir; |
| 85 |
} |
| 86 |
|
| 87 |
private function compile($filename, $expression, $functionName) |
| 88 |
{ |
| 89 |
$code = $this->compiler->visit( |
| 90 |
$this->parser->parse($expression), |
| 91 |
$functionName, |
| 92 |
$expression |
| 93 |
); |
| 94 |
|
| 95 |
$tempFile = $filename . '.' . bin2hex(random_bytes(12)) . '.tmp'; |
| 96 |
|
| 97 |
if (!file_put_contents($tempFile, $code)) { |
| 98 |
throw new \RuntimeException(sprintf( |
| 99 |
'Unable to write the compiled PHP code to: %s (%s)', |
| 100 |
$tempFile, |
| 101 |
var_export(error_get_last(), true) |
| 102 |
)); |
| 103 |
} |
| 104 |
|
| 105 |
if (!rename($tempFile, $filename)) { |
| 106 |
@unlink($tempFile); |
| 107 |
if (!file_exists($filename)) { |
| 108 |
throw new \RuntimeException( |
| 109 |
"Unable to move the compiled PHP code to: {$filename}" |
| 110 |
); |
| 111 |
} |
| 112 |
|
| 113 |
} elseif (function_exists('opcache_invalidate')) { |
| 114 |
opcache_invalidate($filename, true); |
| 115 |
} |
| 116 |
} |
| 117 |
} |