|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * JSONPath implementation for PHP. |
| 5 | + * |
| 6 | + * @license https://github.com/SoftCreatR/JSONPath/blob/main/LICENSE MIT License |
| 7 | + */ |
| 8 | + |
| 9 | +declare(strict_types=1); |
| 10 | + |
| 11 | +namespace Flow\JSONPath\Test; |
| 12 | + |
| 13 | +use Exception; |
| 14 | +use Flow\JSONPath\JSONPath; |
| 15 | +use Flow\JSONPath\Test\Traits\TestDataTrait; |
| 16 | +use PHPUnit\Framework\TestCase; |
| 17 | + |
| 18 | +use function is_array; |
| 19 | +use function random_int; |
| 20 | + |
| 21 | +class JSONPathArrayTest extends TestCase |
| 22 | +{ |
| 23 | + use TestDataTrait; |
| 24 | + |
| 25 | + /** |
| 26 | + * @throws Exception |
| 27 | + */ |
| 28 | + public function testChaining(): void |
| 29 | + { |
| 30 | + $jsonPath = (new JSONPath($this->getData('conferences'))); |
| 31 | + |
| 32 | + $teams = $jsonPath |
| 33 | + ->find('.conferences.*') |
| 34 | + ->find('..teams.*'); |
| 35 | + |
| 36 | + self::assertEquals('Dodger', $teams[0]['name']); |
| 37 | + self::assertEquals('Mets', $teams[1]['name']); |
| 38 | + |
| 39 | + $teams = $jsonPath |
| 40 | + ->find('.conferences.*') |
| 41 | + ->find('..teams.*'); |
| 42 | + |
| 43 | + self::assertEquals('Dodger', $teams[0]['name']); |
| 44 | + self::assertEquals('Mets', $teams[1]['name']); |
| 45 | + |
| 46 | + $teams = $jsonPath |
| 47 | + ->find('.conferences..teams.*'); |
| 48 | + |
| 49 | + self::assertEquals('Dodger', $teams[0]['name']); |
| 50 | + self::assertEquals('Mets', $teams[1]['name']); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * @throws Exception |
| 55 | + */ |
| 56 | + public function testIterating(): void |
| 57 | + { |
| 58 | + $data = $this->getData('conferences'); |
| 59 | + |
| 60 | + $conferences = (new JSONPath($data)) |
| 61 | + ->find('.conferences.*'); |
| 62 | + |
| 63 | + $names = []; |
| 64 | + |
| 65 | + foreach ($conferences as $conference) { |
| 66 | + $players = $conference |
| 67 | + ->find('.teams.*.players[?(@.active=yes)]'); |
| 68 | + |
| 69 | + foreach ($players as $player) { |
| 70 | + $names[] = $player->name; |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + self::assertEquals(['Joe Face', 'something'], $names); |
| 75 | + } |
| 76 | + |
| 77 | + /** |
| 78 | + * @throws Exception |
| 79 | + */ |
| 80 | + public function testDifferentStylesOfAccess(): void |
| 81 | + { |
| 82 | + $data = (new JSONPath($this->getData('conferences', random_int(0, 1)))); |
| 83 | + |
| 84 | + self::assertArrayHasKey('conferences', $data); |
| 85 | + |
| 86 | + $conferences = $data->__get('conferences')->getData(); |
| 87 | + |
| 88 | + if (is_array($conferences[0])) { |
| 89 | + self::assertEquals('Western Conference', $conferences[0]['name']); |
| 90 | + } else { |
| 91 | + self::assertEquals('Western Conference', $conferences[0]->name); |
| 92 | + } |
| 93 | + } |
| 94 | +} |
0 commit comments