| 1 |
<?php |
| 2 |
|
| 3 |
namespace Dudlewebs\WPMCS\s3\JmesPath; |
| 4 |
|
| 5 |
/** |
| 6 |
* Uses an external tree visitor to interpret an AST. |
| 7 |
*/ |
| 8 |
class AstRuntime |
| 9 |
{ |
| 10 |
private $parser; |
| 11 |
private $interpreter; |
| 12 |
private $cache = []; |
| 13 |
private $cachedCount = 0; |
| 14 |
public function __construct(Parser $parser = null, callable $fnDispatcher = null) |
| 15 |
{ |
| 16 |
$fnDispatcher = $fnDispatcher ?: FnDispatcher::getInstance(); |
| 17 |
$this->interpreter = new TreeInterpreter($fnDispatcher); |
| 18 |
$this->parser = $parser ?: new Parser(); |
| 19 |
} |
| 20 |
/** |
| 21 |
* Returns data from the provided input that matches a given JMESPath |
| 22 |
* expression. |
| 23 |
* |
| 24 |
* @param string $expression JMESPath expression to evaluate |
| 25 |
* @param mixed $data Data to search. This data should be data that |
| 26 |
* is similar to data returned from json_decode |
| 27 |
* using associative arrays rather than objects. |
| 28 |
* |
| 29 |
* @return mixed Returns the matching data or null |
| 30 |
*/ |
| 31 |
public function __invoke($expression, $data) |
| 32 |
{ |
| 33 |
if (!isset($this->cache[$expression])) { |
| 34 |
// Clear the AST cache when it hits 1024 entries |
| 35 |
if (++$this->cachedCount > 1024) { |
| 36 |
$this->cache = []; |
| 37 |
$this->cachedCount = 0; |
| 38 |
} |
| 39 |
$this->cache[$expression] = $this->parser->parse($expression); |
| 40 |
} |
| 41 |
return $this->interpreter->visit($this->cache[$expression], $data); |
| 42 |
} |
| 43 |
} |
| 44 |
|