Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c16162f

Browse files
committed
feature #60188 [JsonPath] Add two utils methods to JsonPath builder (alexandre-daubois)
This PR was merged into the 7.3 branch. Discussion ---------- [JsonPath] Add two utils methods to `JsonPath` builder | Q | A | ------------- | --- | Branch? | 7.3 | Bug fix? | no | New feature? | yes | Deprecations? | no | Issues | - | License | MIT Small DX improvements that goes with #60105 and #60083. This PR adds two new methods, `first()` and `last()`, added to JsonPath builder. This voluntary reminds methods from the DomCrawler component. The goal is not to add every possible method, but I think `first()` and `last()` are common enough to be added. I also propose to rename `anyIndex()` to `all()`. ```php $path = new JsonPath(); // Get the first user of the collection $path = $path->key('users')->first(); ``` ```php $path = new JsonPath(); // Get the last user of the collection $path = $path->key('users')->last(); ``` ```php $path = new JsonPath(); // Get all users of the collection $path = $path->key('users')->all(); ``` Commits ------- 3bc3559 [JsonPath][DX] Add utils methods to `JsonPath` builder
2 parents 79fa5f2 + 3bc3559 commit c16162f

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/Symfony/Component/JsonPath/JsonPath.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,21 @@ public function deepScan(): static
4343
return new self($this->path.'..');
4444
}
4545

46-
public function anyIndex(): static
46+
public function all(): static
4747
{
4848
return new self($this->path.'[*]');
4949
}
5050

51+
public function first(): static
52+
{
53+
return new self($this->path.'[0]');
54+
}
55+
56+
public function last(): static
57+
{
58+
return new self($this->path.'[-1]');
59+
}
60+
5161
public function slice(int $start, ?int $end = null, ?int $step = null): static
5262
{
5363
$slice = $start;

src/Symfony/Component/JsonPath/Tests/JsonPathTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,31 @@ public function testBuildWithFilter()
3535

3636
$this->assertSame('$.users[?(@.age > 18)]', (string) $path);
3737
}
38+
39+
public function testAll()
40+
{
41+
$path = new JsonPath();
42+
$path = $path->key('users')
43+
->all();
44+
45+
$this->assertSame('$.users[*]', (string) $path);
46+
}
47+
48+
public function testFirst()
49+
{
50+
$path = new JsonPath();
51+
$path = $path->key('users')
52+
->first();
53+
54+
$this->assertSame('$.users[0]', (string) $path);
55+
}
56+
57+
public function testLast()
58+
{
59+
$path = new JsonPath();
60+
$path = $path->key('users')
61+
->last();
62+
63+
$this->assertSame('$.users[-1]', (string) $path);
64+
}
3865
}

0 commit comments

Comments
 (0)