Skip to content

Commit d1af5f3

Browse files
authored
Create Where.php
1 parent 8a19762 commit d1af5f3

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/Ve/Where.php

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<?php
2+
3+
namespace Ve\Where;
4+
5+
function where($objects, $propertyMap)
6+
{
7+
$result = [];
8+
9+
foreach ($objects as $obj)
10+
{
11+
if (matches($obj, $propertyMap)) {
12+
$result[] = $obj;
13+
}
14+
}
15+
16+
return $result;
17+
}
18+
19+
function matches($object, $propertyMap)
20+
{
21+
foreach ($propertyMap as $property => $value) {
22+
if (is_array($value)) {
23+
if (!matches(readProperty($object, $property), $value)) {
24+
return false;
25+
} else {
26+
continue;
27+
}
28+
}
29+
if (readProperty($object, $property) != $value) {
30+
return false;
31+
}
32+
}
33+
34+
return true;
35+
}
36+
37+
function readProperty($object, $property)
38+
{
39+
if (is_object($object)) {
40+
if (property_exists($object, $property)) {
41+
return $object->$property;
42+
} elseif (method_exists($object, $property)) {
43+
return call_user_func([$object, $property]);
44+
} else {
45+
throw new \InvalidArgumentException(sprintf('Expected property or method %s in %s', $property, get_class($object)));
46+
}
47+
} elseif (is_array($object)) {
48+
return $object[$property];
49+
} else {
50+
throw new \InvalidArgumentException('Expected object or array');
51+
}
52+
}

0 commit comments

Comments
 (0)