Skip to content

Commit 25d7696

Browse files
author
Michal Szczur
committed
#71 Added check if value exists
1 parent 9518da0 commit 25d7696

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

src/Matcher/ArrayMatcher.php

+29-3
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use Coduo\ToString\StringConverter;
77
use Symfony\Component\PropertyAccess\PropertyAccess;
88
use Symfony\Component\PropertyAccess\PropertyAccessor;
9+
use Symfony\Component\PropertyAccess\PropertyPath;
910

1011
final class ArrayMatcher extends Matcher
1112
{
@@ -147,7 +148,7 @@ private function isPatternValid(array $pattern, array $values, $parentPath)
147148

148149
if (count($notExistingKeys) > 0) {
149150
$keyNames = array_keys($notExistingKeys);
150-
$path = $this->formatFullPath($parentPath, $this->formatAccessPath($keyNames[0]));
151+
$path = $this->formatFullPath($parentPath, $this->formatAccessPath($keyNames[0]));
151152
$this->setMissingElementInError('value', $path);
152153
return false;
153154
}
@@ -180,7 +181,33 @@ private function valueMatchPattern($value, $pattern)
180181
*/
181182
private function valueExist($path, array $haystack)
182183
{
183-
return $this->getPropertyAccessor()->isReadable($haystack, $path);
184+
$propertyPath = new PropertyPath($path);
185+
$length = $propertyPath->getLength();
186+
$valueExist = true;
187+
for ($i = 0; $i < $length; ++$i) {
188+
$property = $propertyPath->getElement($i);
189+
$isIndex = $propertyPath->isIndex($i);
190+
$propertyExist = $this->arrayPropertyExists($property, $haystack);
191+
192+
if ($isIndex && !$propertyExist) {
193+
$valueExist = false;
194+
break;
195+
}
196+
}
197+
198+
unset($propertyPath);
199+
return $valueExist;
200+
}
201+
202+
/**
203+
* @param string $property
204+
* @param array $objectOrArray
205+
* @return bool
206+
*/
207+
private function arrayPropertyExists($property, array $objectOrArray)
208+
{
209+
return ($objectOrArray instanceof \ArrayAccess && isset($objectOrArray[$property])) ||
210+
(is_array($objectOrArray) && array_key_exists($property, $objectOrArray));
184211
}
185212

186213
/**
@@ -203,7 +230,6 @@ private function getPropertyAccessor()
203230
}
204231

205232
$accessorBuilder = PropertyAccess::createPropertyAccessorBuilder();
206-
$accessorBuilder->enableExceptionOnInvalidIndex();
207233
$this->accessor = $accessorBuilder->getPropertyAccessor();
208234

209235
return $this->accessor;

0 commit comments

Comments
 (0)