Skip to content

Commit 95f9595

Browse files
committed
Improved jsonpath for array elements
1 parent c106a55 commit 95f9595

2 files changed

Lines changed: 15 additions & 6 deletions

File tree

src/Validator.php

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,8 @@ protected function getBuiltInTypeValidators()
4444
}
4545

4646
$givenType = $this->getType($value);
47-
$path = implode('.', $this->path);
47+
48+
$path = $this->getNormalizedPath();
4849

4950
$this->addError($path, "The path of '$path' requires to be a $type, $givenType is given");
5051

@@ -101,6 +102,14 @@ public function addType(string $type, $definition)
101102
protected $errors = [];
102103
protected $path = ['$'];
103104

105+
protected function getNormalizedPath()
106+
{
107+
return strtr(implode('.', $this->path), [
108+
'.[' => '[',
109+
'].' => ']',
110+
]);
111+
}
112+
104113
public function getErrors()
105114
{
106115
return $this->errors;
@@ -152,7 +161,7 @@ protected function matchArray(array $data, $definition)
152161
$definition = $definition[0];
153162

154163
foreach ($data as $index => $row) {
155-
array_push($this->path, $index);
164+
array_push($this->path, '[' . $index . ']');
156165
$result = $this->matchInternal($row, $definition);
157166
array_pop($this->path);
158167

tests/JsonTypeTest.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -153,8 +153,8 @@ public function typeErrorMessages()
153153
[
154154
[1, 2, 3],
155155
['string'],
156-
'$.0',
157-
"The path of '$.0' requires to be a string, integer is given",
156+
'$[0]',
157+
"The path of '$[0]' requires to be a string, integer is given",
158158
],
159159
[
160160
[
@@ -163,8 +163,8 @@ public function typeErrorMessages()
163163
[
164164
'foo' => ['string'],
165165
],
166-
'$.foo.0',
167-
"The path of '$.foo.0' requires to be a string, integer is given",
166+
'$.foo[0]',
167+
"The path of '$.foo[0]' requires to be a string, integer is given",
168168
],
169169
];
170170
}

0 commit comments

Comments
 (0)