Skip to content

Commit

Permalink
[10.x] Allow multiple types in Collection's ensure method (#49127)
Browse files Browse the repository at this point in the history
* Add ability to pass multiple types to Collection "ensure" method.

* Update docblock.

* Fixed typo.
  • Loading branch information
ash-jc-allen authored Nov 26, 2023
1 parent 38b897f commit d3e3667
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/Illuminate/Collections/Traits/EnumeratesValues.php
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ public function value($key, $default = null)
*
* @template TEnsureOfType
*
* @param class-string<TEnsureOfType> $type
* @param class-string<TEnsureOfType>|array<array-key, class-string<TEnsureOfType>> $type
* @return static<TKey, TEnsureOfType>
*
* @throws \UnexpectedValueException
Expand All @@ -331,11 +331,17 @@ public function ensure($type)
return $this->each(function ($item) use ($type) {
$itemType = get_debug_type($item);

if ($itemType !== $type && ! $item instanceof $type) {
throw new UnexpectedValueException(
sprintf("Collection should only include '%s' items, but '%s' found.", $type, $itemType)
);
$allowedTypes = is_array($type) ? $type : [$type];

foreach ($allowedTypes as $allowedType) {
if ($itemType === $allowedType || $item instanceof $allowedType) {
return true;
}
}

throw new UnexpectedValueException(
sprintf("Collection should only include [%s] items, but '%s' found.", implode(', ', $allowedTypes), $itemType)
);
});
}

Expand Down
13 changes: 13 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5647,6 +5647,19 @@ public function testEnsureForInheritance($collection)
$data->ensure(\Throwable::class);
}

/**
* @dataProvider collectionClassProvider
*/
public function testEnsureForMultipleTypes($collection)
{
$data = $collection::make([new \Error, 123]);
$data->ensure([\Throwable::class, 'int']);

$data = $collection::make([new \Error, new \Error, new $collection]);
$this->expectException(UnexpectedValueException::class);
$data->ensure([\Throwable::class, 'int']);
}

/**
* @dataProvider collectionClassProvider
*/
Expand Down

0 comments on commit d3e3667

Please sign in to comment.