Skip to content

Commit

Permalink
[10.x] Throw exception when trying to initiate Collection using `We…
Browse files Browse the repository at this point in the history
…akMap` (#49095)

* [10.x] Throw exception when trying to initiate `Collection` using `WeakMap`

fixes #49089

Signed-off-by: Mior Muhammad Zaki <[email protected]>

* Apply fixes from StyleCI

* wip

Signed-off-by: Mior Muhammad Zaki <[email protected]>

* Update SupportCollectionTest.php

* Update EnumeratesValues.php

---------

Signed-off-by: Mior Muhammad Zaki <[email protected]>
Co-authored-by: StyleCI Bot <[email protected]>
Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
3 people authored Nov 23, 2023
1 parent 60f753f commit b99d035
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
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

0 comments on commit b99d035

Please sign in to comment.