JSONPathArrayAccessTest.php 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace Flow\JSONPath\Test;
  3. use Flow\JSONPath\JSONPath;
  4. use PHPUnit\Framework\TestCase;
  5. require_once __DIR__ . "/../vendor/autoload.php";
  6. class JSONPathArrayAccessTest extends TestCase
  7. {
  8. public function testChaining()
  9. {
  10. $data = $this->exampleData(rand(0, 1));
  11. $conferences = (new JSONPath($data))->find('.conferences.*');
  12. $teams = $conferences->find('..teams.*');
  13. $this->assertEquals('Dodger', $teams[0]['name']);
  14. $this->assertEquals('Mets', $teams[1]['name']);
  15. $teams = (new JSONPath($data))->find('.conferences.*')->find('..teams.*');
  16. $this->assertEquals('Dodger', $teams[0]['name']);
  17. $this->assertEquals('Mets', $teams[1]['name']);
  18. $teams = (new JSONPath($data))->find('.conferences..teams.*');
  19. $this->assertEquals('Dodger', $teams[0]['name']);
  20. $this->assertEquals('Mets', $teams[1]['name']);
  21. }
  22. public function testIterating()
  23. {
  24. $data = $this->exampleData(rand(0, 1));
  25. $conferences = (new JSONPath($data))->find('.conferences.*');
  26. $names = [];
  27. foreach ($conferences as $conference) {
  28. $players = $conference->find('.teams.*.players[?(@.active=yes)]');
  29. foreach ($players as $player) {
  30. $names[] = $player->name;
  31. }
  32. }
  33. $this->assertEquals(['Joe Face', 'something'], $names);
  34. }
  35. public function testDifferentStylesOfAccess()
  36. {
  37. $data = $this->exampleData(rand(0, 1));
  38. $league = new JSONPath($data);
  39. $conferences = $league->conferences;
  40. $firstConference = $league->conferences[0];
  41. $this->assertEquals('Western Conference', $firstConference->name);
  42. }
  43. public function exampleData($asArray = true)
  44. {
  45. $data = [
  46. 'name' => 'Major League Baseball',
  47. 'abbr' => 'MLB',
  48. 'conferences' => [
  49. [
  50. 'name' => 'Western Conference',
  51. 'abbr' => 'West',
  52. 'teams' => [
  53. [
  54. 'name' => 'Dodger',
  55. 'city' => 'Los Angeles',
  56. 'whatever' => 'else',
  57. 'players' => [
  58. ['name' => 'Bob Smith', 'number' => 22],
  59. ['name' => 'Joe Face', 'number' => 23, 'active' => 'yes'],
  60. ],
  61. ]
  62. ],
  63. ],
  64. [
  65. 'name' => 'Eastern Conference',
  66. 'abbr' => 'East',
  67. 'teams' => [
  68. [
  69. 'name' => 'Mets',
  70. 'city' => 'New York',
  71. 'whatever' => 'else',
  72. 'players' => [
  73. ['name' => 'something', 'number' => 14, 'active' => 'yes'],
  74. ['name' => 'something', 'number' => 15],
  75. ]
  76. ]
  77. ]
  78. ]
  79. ]
  80. ];
  81. return $asArray ? $data : json_decode(json_encode($data));
  82. }
  83. }