JSONPathArrayAccessTest.php 3.2 KB

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