Skip to content

Commit

Permalink
[10.x] Update ensure() collection method to correctly work with Inter…
Browse files Browse the repository at this point in the history
…faces and object inheritance (#47934)

* Update ensure() collection method to correctly work with Interfaces and object inheritance.

* corrections to style
  • Loading branch information
karpilin authored Aug 2, 2023
1 parent 56d59a7 commit 119840d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 8 deletions.
12 changes: 7 additions & 5 deletions src/Illuminate/Collections/Traits/EnumeratesValues.php
Original file line number Diff line number Diff line change
Expand Up @@ -315,10 +315,10 @@ public function value($key, $default = null)
/**
* Ensure that every item in the collection is of the expected type.
*
* @template TEnforceIntoValue
* @template TEnsureOfType
*
* @param class-string<TEnforceIntoValue> $type
* @return static<mixed, TEnforceIntoValue>
* @param class-string<TEnsureOfType> $type
* @return static<mixed, TEnsureOfType>
*
* @throws \UnexpectedValueException
*/
Expand All @@ -327,8 +327,10 @@ public function ensure($type)
return $this->each(function ($item) use ($type) {
$itemType = get_debug_type($item);

if ($itemType !== $type) {
throw new UnexpectedValueException("Collection should only include '{$type}' items, but '{$itemType}' found.");
if ($itemType !== $type && ! $item instanceof $type) {
throw new UnexpectedValueException(
sprintf("Collection should only include '%s' items, but '%s' found.", $type, $itemType)
);
}
});
}
Expand Down
29 changes: 26 additions & 3 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5598,17 +5598,40 @@ public function testDot($collection)
/**
* @dataProvider collectionClassProvider
*/
public function testEnsure($collection)
public function testEnsureForScalar($collection)
{
$data = $collection::make([1, 2, 3]);

$data->ensure('int');

$data = $collection::make([1, 2, 3, 'foo']);
$this->expectException(UnexpectedValueException::class);
$data->ensure('int');
}

/**
* @dataProvider collectionClassProvider
*/
public function testEnsureForObjects($collection)
{
$data = $collection::make([new stdClass, new stdClass, new stdClass]);
$data->ensure(stdClass::class);

$data = $collection::make([new stdClass, new stdClass, new stdClass, $collection]);
$this->expectException(UnexpectedValueException::class);
$data->ensure(stdClass::class);
}

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

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

/**
Expand Down

0 comments on commit 119840d

Please sign in to comment.