- Added callable field in search, searchOne, remove, removeOne, etc...

This commit is contained in:
Dave Mc Nicoll committed 2025-06-26 14:34:12 +00:00
1 parent a5d65025f8
commit 2f482324b2
2 files changed
+99 -8

No files matched your search

+14 -7
View File
@@ -100,7 +100,7 @@ class EntityCollection extends \ArrayObject implements \JsonSerializable {
return $this;
}
public function removeOne($value, string $field, bool $strict = true) : ? object
public function removeOne($value, callable|string $field, bool $strict = true) : ? object
{
foreach($this->search($value, $field, $strict) as $key => $item) {
$this->offsetUnset($key);
@@ -111,7 +111,7 @@ class EntityCollection extends \ArrayObject implements \JsonSerializable {
return null;
}
public function remove(/* mixed */ $value, string $field, bool $strict = true) : array
public function remove(/* mixed */ $value, callable|string $field, bool $strict = true) : array
{
$removed = [];
@@ -131,14 +131,21 @@ class EntityCollection extends \ArrayObject implements \JsonSerializable {
return $this;
}
public function search(mixed $value, string $field, bool $strict = true) : Generator
public function search(mixed $value, callable|string $field, bool $strict = true) : Generator
{
foreach($this->filters(fn($v) => isset($v->$field) ? ( $strict ? $v->$field === $value : $v->$field == $value ) : false) as $key => $item) {
if (is_string($field)) {
$filtering = fn($v) => isset($v->$field) ? ($strict ? $v->$field === $value : $v->$field == $value) : false;
}
elseif (is_callable($field)) {
$filtering = fn($v) => ( $fieldValue = call_user_func($field, $v) ) !== null ? ($strict ? $fieldValue === $value : $fieldValue == $value) : false;
}
foreach($this->filters($filtering) as $key => $item) {
yield $key => $item;
}
}
public function searchOne(mixed $value, string $field, bool $strict = true) : ? object
public function searchOne(mixed $value, callable|string $field, bool $strict = true) : ? object
{
# Returning first value only
foreach($this->search($value, $field, $strict) as $item) {
@@ -148,7 +155,7 @@ class EntityCollection extends \ArrayObject implements \JsonSerializable {
return null;
}
public function searchAll(mixed $values, string $field, bool $strict = true, bool $compareArray = false) : self
public function searchAll(mixed $values, callable|string $field, bool $strict = true, bool $compareArray = false) : self
{
$collection = new static();
@@ -163,7 +170,7 @@ class EntityCollection extends \ArrayObject implements \JsonSerializable {
return $collection;
}
public function diffAll(mixed $values, string $field, bool $strict = true, bool $compareArray = false) : self
public function diffAll(mixed $values, callable|string $field, bool $strict = true, bool $compareArray = false) : self
{
$obj = new static($this->getArrayCopy());