From d3e3667cb6a1513a702713170e7d05cc649202ed Mon Sep 17 00:00:00 2001 From: Ash Allen Date: Sun, 26 Nov 2023 15:55:12 +0000 Subject: [PATCH] [10.x] Allow multiple types in Collection's `ensure` method (#49127) * Add ability to pass multiple types to Collection "ensure" method. * Update docblock. * Fixed typo. --- .../Collections/Traits/EnumeratesValues.php | 16 +++++++++++----- tests/Support/SupportCollectionTest.php | 13 +++++++++++++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/Illuminate/Collections/Traits/EnumeratesValues.php b/src/Illuminate/Collections/Traits/EnumeratesValues.php index b42edb49d808..ceaed53c1ba4 100644 --- a/src/Illuminate/Collections/Traits/EnumeratesValues.php +++ b/src/Illuminate/Collections/Traits/EnumeratesValues.php @@ -321,7 +321,7 @@ public function value($key, $default = null) * * @template TEnsureOfType * - * @param class-string $type + * @param class-string|array> $type * @return static * * @throws \UnexpectedValueException @@ -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) + ); }); } diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 55fb1359d19c..dc82699b9329 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -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 */