AstRuntime.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. namespace JmesPath;
  3. /**
  4. * Uses an external tree visitor to interpret an AST.
  5. */
  6. class AstRuntime
  7. {
  8. private $parser;
  9. private $interpreter;
  10. private $cache = [];
  11. private $cachedCount = 0;
  12. public function __construct(
  13. Parser $parser = null,
  14. 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. }