jp.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/env php
  2. <?php
  3. require __DIR__ . '/../vendor/autoload.php';
  4. use JmesPath\Env;
  5. use JmesPath\DebugRuntime;
  6. $description = <<<EOT
  7. Runs a JMESPath expression on the provided input or a test case.
  8. Provide the JSON input and expression:
  9. echo '{}' | jp.php expression
  10. Or provide the path to a compliance script, a suite, and test case number:
  11. jp.php --script path_to_script --suite test_suite_number --case test_case_number [expression]
  12. EOT;
  13. $args = [];
  14. $currentKey = null;
  15. for ($i = 1, $total = count($argv); $i < $total; $i++) {
  16. if ($i % 2) {
  17. if (substr($argv[$i], 0, 2) == '--') {
  18. $currentKey = str_replace('--', '', $argv[$i]);
  19. } else {
  20. $currentKey = trim($argv[$i]);
  21. }
  22. } else {
  23. $args[$currentKey] = $argv[$i];
  24. $currentKey = null;
  25. }
  26. }
  27. $expression = $currentKey;
  28. if (isset($args['file']) || isset($args['suite']) || isset($args['case'])) {
  29. if (!isset($args['file']) || !isset($args['suite']) || !isset($args['case'])) {
  30. die($description);
  31. }
  32. // Manually run a compliance test
  33. $path = realpath($args['file']);
  34. file_exists($path) or die('File not found at ' . $path);
  35. $json = json_decode(file_get_contents($path), true);
  36. $set = $json[$args['suite']];
  37. $data = $set['given'];
  38. if (!isset($expression)) {
  39. $expression = $set['cases'][$args['case']]['expression'];
  40. echo "Expects\n=======\n";
  41. if (isset($set['cases'][$args['case']]['result'])) {
  42. echo json_encode($set['cases'][$args['case']]['result'], JSON_PRETTY_PRINT) . "\n\n";
  43. } elseif (isset($set['cases'][$args['case']]['error'])) {
  44. echo "{$set['cases'][$argv['case']]['error']} error\n\n";
  45. } else {
  46. echo "NULL\n\n";
  47. }
  48. }
  49. } elseif (isset($expression)) {
  50. // Pass in an expression and STDIN as a standalone argument
  51. $data = json_decode(stream_get_contents(STDIN), true);
  52. } else {
  53. die($description);
  54. }
  55. $runtime = new DebugRuntime(Env::createRuntime());
  56. $runtime($expression, $data);