/**
  * Check if the given emitter has the provided event listener.
  *
  * @param EmitterInterface $emitter Emitter to search
  * @param string|object    $value   Can be a class name or listener object
  * @param null             $event   Specific event to search (optional)
  *
  * @return bool
  */
 public static function hasListener(EmitterInterface $emitter, $value, $event = null)
 {
     $expression = $event ? '[*][0]' : '*[*][0]';
     $listeners = $event ? $emitter->listeners($event) : $emitter->listeners();
     $result = JmesPath::search($expression, $listeners) ?: [];
     if (!is_object($value)) {
         $result = array_map(function ($o) {
             return get_class($o);
         }, $result);
     }
     return in_array($value, $result, true);
 }
 /**
  * @param array $mapping
  * @return array
  */
 public function extractData(array $mapping)
 {
     $result = [];
     foreach ($mapping as $fieldName => $expression) {
         $result[$fieldName] = \JmesPath\Env::search($expression, $this->apiData);
     }
     return $result;
 }
 public function testCleansCompileDir()
 {
     $dir = sys_get_temp_dir();
     $runtime = new CompilerRuntime($dir);
     $runtime('@ | @ | @[0][0][0]', []);
     $this->assertNotEmpty(glob($dir . '/jmespath_*.php'));
     $this->assertGreaterThan(0, Env::cleanCompileDir());
     $this->assertEmpty(glob($dir . '/jmespath_*.php'));
 }
Example #4
0
 /**
  * {@inheritdoc}
  */
 public function getFunctions()
 {
     $compiler = function () {
         throw new LogicException('Compilation not supported.');
     };
     return [new ExpressionFunction('url', $compiler, function ($arguments, $url) {
         return $url;
     }), new ExpressionFunction('link', $compiler, function ($arguments, $selector) {
         return $arguments['_crawler']->selectLink($selector);
     }), new ExpressionFunction('button', $compiler, function ($arguments, $selector) {
         return $arguments['_crawler']->selectButton($selector);
     }), new ExpressionFunction('status_code', $compiler, function ($arguments) {
         return $arguments['_response']->getStatusCode();
     }), new ExpressionFunction('headers', $compiler, function ($arguments) {
         $headers = [];
         foreach ($arguments['_response']->getHeaders() as $key => $value) {
             $headers[$key] = $value[0];
         }
         return $headers;
     }), new ExpressionFunction('body', $compiler, function ($arguments) {
         return (string) $arguments['_response']->getBody();
     }), new ExpressionFunction('header', $compiler, function ($arguments, $name) {
         $name = str_replace('_', '-', strtolower($name));
         if (!$arguments['_response']->hasHeader($name)) {
             return;
         }
         return $arguments['_response']->getHeader($name)[0];
     }), new ExpressionFunction('scalar', $compiler, function ($arguments, $string) {
         return $string;
     }), new ExpressionFunction('css', $compiler, function ($arguments, $selector) {
         if (null === $arguments['_crawler']) {
             throw new LogicException(sprintf('Unable to get "%s" CSS selector as the page is not crawlable.', $selector));
         }
         return $arguments['_crawler']->filter($selector);
     }), new ExpressionFunction('xpath', $compiler, function ($arguments, $selector) {
         if (null === $arguments['_crawler']) {
             throw new LogicException(sprintf('Unable to get "%s" XPATH selector as the page is not crawlable.', $selector));
         }
         return $arguments['_crawler']->filterXPath($selector);
     }), new ExpressionFunction('json', $compiler, function ($arguments, $selector) {
         if (null === ($data = json_decode((string) $arguments['_response']->getBody(), true))) {
             throw new LogicException(sprintf(' Unable to get the "%s" JSON path as the Response body does not seem to be JSON.', $selector));
         }
         return JmesPath::search($selector, $data);
     })];
 }
Example #5
0
function runCase($given, $expression, $name)
{
    $best = 99999;
    $runtime = \JmesPath\Env::createRuntime();
    for ($i = 0; $i < 100; $i++) {
        $t = microtime(true);
        $runtime($expression, $given);
        $tryTime = (microtime(true) - $t) * 1000;
        if ($tryTime < $best) {
            $best = $tryTime;
        }
        if (!getenv('CACHE')) {
            $runtime = \JmesPath\Env::createRuntime();
            // Delete compiled scripts if not caching.
            if ($runtime instanceof \JmesPath\CompilerRuntime) {
                array_map('unlink', glob(sys_get_temp_dir() . '/jmespath_*.php'));
            }
        }
    }
    printf("time: %07.4fms name: %s\n", $best, $name);
    return $best;
}
Example #6
0
}
$expression = $currentKey;
if (isset($args['file']) || isset($args['suite']) || isset($args['case'])) {
    if (!isset($args['file']) || !isset($args['suite']) || !isset($args['case'])) {
        die($description);
    }
    // Manually run a compliance test
    $path = realpath($args['file']);
    file_exists($path) or die('File not found at ' . $path);
    $json = json_decode(file_get_contents($path), true);
    $set = $json[$args['suite']];
    $data = $set['given'];
    if (!isset($expression)) {
        $expression = $set['cases'][$args['case']]['expression'];
        echo "Expects\n=======\n";
        if (isset($set['cases'][$args['case']]['result'])) {
            echo json_encode($set['cases'][$args['case']]['result'], JSON_PRETTY_PRINT) . "\n\n";
        } elseif (isset($set['cases'][$args['case']]['error'])) {
            echo "{$set['cases'][$argv['case']]['error']} error\n\n";
        } else {
            echo "NULL\n\n";
        }
    }
} elseif (isset($expression)) {
    // Pass in an expression and STDIN as a standalone argument
    $data = json_decode(stream_get_contents(STDIN), true);
} else {
    die($description);
}
$runtime = new DebugRuntime(Env::createRuntime());
$runtime($expression, $data);
Example #7
0
 /**
  * {@inheritdoc}
  */
 public function getFunctions()
 {
     $compiler = function () {
         throw new LogicException('Compilation not supported.');
     };
     return [new ExpressionFunction('url', $compiler, function ($arguments, $url) {
         return $url;
     }), new ExpressionFunction('link', $compiler, function ($arguments, $selector) {
         return $arguments['_crawler']->selectLink($selector);
     }), new ExpressionFunction('button', $compiler, function ($arguments, $selector) {
         return $arguments['_crawler']->selectButton($selector);
     }), new ExpressionFunction('status_code', $compiler, function ($arguments) {
         return $arguments['_response']->getStatusCode();
     }), new ExpressionFunction('headers', $compiler, function ($arguments) {
         $headers = [];
         foreach ($arguments['_response']->getHeaders() as $key => $value) {
             $headers[$key] = $value[0];
         }
         return $headers;
     }), new ExpressionFunction('body', $compiler, function ($arguments) {
         return (string) $arguments['_response']->getBody();
     }), new ExpressionFunction('header', $compiler, function ($arguments, $name) {
         $name = str_replace('_', '-', strtolower($name));
         if (!$arguments['_response']->hasHeader($name)) {
             return;
         }
         return $arguments['_response']->getHeader($name)[0];
     }), new ExpressionFunction('scalar', $compiler, function ($arguments, $scalar) {
         return $scalar;
     }), new ExpressionFunction('join', $compiler, function ($arguments, $value, $glue) {
         if ($value instanceof \Traversable) {
             $value = iterator_to_array($value, false);
         }
         return implode($glue, (array) $value);
     }), new ExpressionFunction('fake', $compiler, function ($arguments, $provider) {
         $arguments = func_get_args();
         return $this->faker->format($provider, array_splice($arguments, 2));
     }), new ExpressionFunction('regex', $compiler, function ($arguments, $regex) {
         $ret = @preg_match($regex, (string) $arguments['_response']->getBody(), $matches);
         if (false === $ret) {
             throw new InvalidArgumentException(sprintf('Regex "%s" is not valid: %s.', $regex, error_get_last()['message']));
         }
         return isset($matches[1]) ? $matches[1] : null;
     }), new ExpressionFunction('css', $compiler, function ($arguments, $selector) {
         if (null === $arguments['_crawler']) {
             throw new LogicException(sprintf('Unable to get "%s" CSS selector as the page is not crawlable.', $selector));
         }
         return $arguments['_crawler']->filter($selector);
     }), new ExpressionFunction('xpath', $compiler, function ($arguments, $selector) {
         if (null === $arguments['_crawler']) {
             throw new LogicException(sprintf('Unable to get "%s" XPATH selector as the page is not crawlable.', $selector));
         }
         return $arguments['_crawler']->filterXPath($selector);
     }), new ExpressionFunction('json', $compiler, function ($arguments, $selector) {
         if (null === ($data = json_decode((string) $arguments['_response']->getBody(), true))) {
             throw new LogicException(sprintf(' Unable to get the "%s" JSON path as the Response body does not seem to be JSON.', $selector));
         }
         return JmesPath::search($selector, $data);
     })];
 }
 public function search($expression)
 {
     return JmesPath::search($expression, $this->toArray());
 }
 public function extractValues($expression)
 {
     return JmesPath::search($expression, $this->getValues());
 }
Example #10
0
 /**
  * Allows to search for specific data values via JMESPath expressions.
  *
  * Some example expressions as a quick start:
  *
  * - "nested.key"           returns the value of the nested "key"
  * - "nested.*"             returns all values available under the "nested" key
  * - "*.key"                returns all values of "key"s on any second level array
  * - "[key, nested.key]"    returns first level "key" value and the first value of the "nested" key array
  * - "[key, nested[0]"      returns first level "key" value and the first value of the "nested" key array
  * - "nested.key || key"    returns the value of the first matching expression
  *
  * @see http://jmespath.readthedocs.org/en/latest/ and https://github.com/mtdowling/jmespath.php
  *
  * @param string $expression JMESPath expression to evaluate on stored data
  *
  * @return mixed|null data in various types (scalar, array etc.) depending on the found results
  *
  * @throws \JmesPath\SyntaxErrorException on invalid expression syntax
  * @throws \RuntimeException e.g. if JMESPath cache directory cannot be written
  * @throws \InvalidArgumentException e.g. if JMESPath builtin functions can't be called
  */
 public function getValues($expression = '*')
 {
     return JmesPath::search($expression, $this->toArray());
 }
Example #11
0
 /**
  * @param string $expression
  * @return mixed|null
  */
 public function search($expression)
 {
     return JmesPath::search($expression, $this->data);
 }
Example #12
0
 /**
  * @param string $expression
  * @param boolean $failOnNull
  * @return mixed|null
  */
 protected function search($expression, $failOnNull = false)
 {
     $result = JmesPath::search($expression, $this->getResults());
     if ($result === null && $failOnNull === true) {
         throw new Exception\RuntimeException(sprintf('Result does not contain "%s"', $expression));
     }
     return $result;
 }
 public function search(Json $json, $pathExpression)
 {
     return \JmesPath\Env::search($pathExpression, $json->getRawContent());
 }
Example #14
0
 /**
  * Asserts if the value retrieved with the expression equals the expected value.
  *
  * Example:
  *
  *     static::assertJsonValueEquals(33, 'foo.bar[0]', $json);
  *
  * @param mixed        $expected   Expected value
  * @param string       $expression Expression to retrieve the result
  *                                 (e.g. locations[?state == 'WA'].name | sort(@))
  * @param array|object $json       JSON Content
  */
 public static function assertJsonValueEquals($expected, $expression, $json)
 {
     $result = \JmesPath\Env::search($expression, $json);
     \PHPUnit_Framework_Assert::assertEquals($expected, $result);
     \PHPUnit_Framework_Assert::assertInternalType(gettype($expected), $result);
 }