Skip to content

Commit c7defa4

Browse files
committed
Add support for array values in filterBy() for 'equal' and 'notEqual'.
1 parent c3e9527 commit c7defa4

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

src/DataListTrait.php

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -649,6 +649,21 @@ private function internalDataListUpdateData($data, $actions): array
649649
return false;
650650
};
651651

652+
$sortAndSerializeArray = function ($data) {
653+
$walkData = function ($data) use (&$walkData) {
654+
$result = [];
655+
foreach ($data as $key => $value) {
656+
if (is_array($value)) {
657+
$value = $walkData($value);
658+
}
659+
$result[$key] = $value;
660+
}
661+
ksort($result);
662+
return $result;
663+
};
664+
return serialize($walkData($data));
665+
};
666+
652667
$pendingNotStartWithFilters = [];
653668
$processPendingNotStartWithFilters = function () use (&$data, &$pendingNotStartWithFilters, &$buildPrefixesIndex, &$existsInPrefixesIndex) {
654669
if (!empty($pendingNotStartWithFilters)) {
@@ -721,9 +736,17 @@ private function internalDataListUpdateData($data, $actions): array
721736
if (!$add) {
722737
$value = $object->$propertyName;
723738
if ($operator === 'equal') {
724-
$add = $value === $targetValue;
739+
if (is_array($value) && is_array($targetValue)) {
740+
$add = $sortAndSerializeArray($value) === $sortAndSerializeArray($targetValue);
741+
} else {
742+
$add = $value === $targetValue;
743+
}
725744
} elseif ($operator === 'notEqual') {
726-
$add = $value !== $targetValue;
745+
if (is_array($value) && is_array($targetValue)) {
746+
$add = $sortAndSerializeArray($value) !== $sortAndSerializeArray($targetValue);
747+
} else {
748+
$add = $value !== $targetValue;
749+
}
727750
} elseif ($operator === 'regExp') {
728751
$add = preg_match('/' . $targetValue . '/', $value) === 1;
729752
} elseif ($operator === 'notRegExp') {

tests/DataListTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,19 @@ function () {
464464
$this->assertTrue($list[1]->other === 2);
465465
$this->assertTrue(count($list) === 2);
466466

467+
$data = [
468+
['value' => ['a' => 1, 'b' => ['b1' => 1, 'b2' => 2]], 'other' => 1],
469+
['other' => 2],
470+
function () {
471+
return ['value' => ['b' => ['b2' => 2, 'b1' => 1], 'a' => 1], 'other' => 3];
472+
}
473+
];
474+
$list = new DataList($data);
475+
$list->filterBy('value', ['a' => 1, 'b' => ['b1' => 1, 'b2' => 2]], 'equal');
476+
$this->assertTrue($list[0]->other === 1);
477+
$this->assertTrue($list[1]->other === 3);
478+
$this->assertTrue(count($list) === 2);
479+
467480

468481
$data = [
469482
['value' => null, 'other' => 1],

0 commit comments

Comments
 (0)