Skip to content

Commit

Permalink
[8.x] Added the whereInstanceOfAny() method for collections (#36328)
Browse files Browse the repository at this point in the history
* Added the whereInstanceOfAny() method for collections.

* Moved whereInstanceOfAny logic into whereInstanceOf method.

* Added tests for using whereInstanceOf with an array.
  • Loading branch information
ash-jc-allen authored Feb 21, 2021
1 parent bb9078a commit ed3a8db
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
4 changes: 2 additions & 2 deletions src/Illuminate/Collections/Enumerable.php
Original file line number Diff line number Diff line change
Expand Up @@ -415,9 +415,9 @@ public function whereNotIn($key, $values, $strict = false);
public function whereNotInStrict($key, $values);

/**
* Filter the items, removing any items that don't match the given type.
* Filter the items, removing any items that don't match the given type(s).
*
* @param string $type
* @param string|string[] $type
* @return static
*/
public function whereInstanceOf($type);
Expand Down
14 changes: 12 additions & 2 deletions src/Illuminate/Collections/Traits/EnumeratesValues.php
Original file line number Diff line number Diff line change
Expand Up @@ -669,14 +669,24 @@ public function whereNotInStrict($key, $values)
}

/**
* Filter the items, removing any items that don't match the given type.
* Filter the items, removing any items that don't match the given type(s).
*
* @param string $type
* @param string|string[] $type
* @return static
*/
public function whereInstanceOf($type)
{
return $this->filter(function ($value) use ($type) {
if (is_array($type)) {
foreach ($type as $classType) {
if ($value instanceof $classType) {
return true;
}
}

return false;
}

return $value instanceof $type;
});
}
Expand Down
4 changes: 3 additions & 1 deletion tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -766,8 +766,10 @@ public function testWhereStrict($collection)
*/
public function testWhereInstanceOf($collection)
{
$c = new $collection([new stdClass, new stdClass, new $collection, new stdClass]);
$c = new $collection([new stdClass, new stdClass, new $collection, new stdClass, new Str]);
$this->assertCount(3, $c->whereInstanceOf(stdClass::class));

$this->assertCount(4, $c->whereInstanceOf([stdClass::class, Str::class]));
}

/**
Expand Down

0 comments on commit ed3a8db

Please sign in to comment.