Skip to content

[10.x] Throw exception when trying to initiate Collection using WeakMap #49095

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Nov 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/Illuminate/Collections/Traits/EnumeratesValues.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@
use Illuminate\Support\Collection;
use Illuminate\Support\Enumerable;
use Illuminate\Support\HigherOrderCollectionProxy;
use InvalidArgumentException;
use JsonSerializable;
use Symfony\Component\VarDumper\VarDumper;
use Traversable;
use UnexpectedValueException;
use UnitEnum;
use WeakMap;

/**
* @template TKey of array-key
Expand Down Expand Up @@ -1019,6 +1021,7 @@ protected function getArrayableItems($items)
}

return match (true) {
$items instanceof WeakMap => throw new InvalidArgumentException('Collections can not be created using instances of WeakMap.'),
$items instanceof Enumerable => $items->all(),
$items instanceof Arrayable => $items->toArray(),
$items instanceof Traversable => iterator_to_array($items),
Expand Down
15 changes: 15 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,14 @@
use IteratorAggregate;
use JsonSerializable;
use Mockery as m;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use stdClass;
use Symfony\Component\VarDumper\VarDumper;
use Traversable;
use UnexpectedValueException;
use WeakMap;

include_once 'Enums.php';

Expand Down Expand Up @@ -2957,6 +2959,19 @@ public function testConstructMethodFromObject($collection)
$this->assertEquals(['foo' => 'bar'], $data->all());
}

#[DataProvider('collectionClassProvider')]
public function testConstructMethodFromWeakMap($collection)
{
$this->expectException('InvalidArgumentException');

$map = new WeakMap();
$object = new stdClass;
$object->foo = 'bar';
$map[$object] = 3;

$data = new $collection($map);
}

public function testSplice()
{
$data = new Collection(['foo', 'baz']);
Expand Down