From 6b101a16ebe991a834d81dc38b2b01356a476e28 Mon Sep 17 00:00:00 2001 From: Davey Shafik Date: Mon, 3 Feb 2025 20:45:30 -0800 Subject: [PATCH] feat: Add support for var_export() to Collection --- src/Bag/Collection.php | 14 ++++++++++++++ tests/Feature/CollectionTest.php | 23 +++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/Bag/Collection.php b/src/Bag/Collection.php index beebd61..2ec997f 100644 --- a/src/Bag/Collection.php +++ b/src/Bag/Collection.php @@ -9,6 +9,7 @@ use Bag\Pipelines\OutputCollectionPipeline; use Bag\Pipelines\Values\CollectionOutput; use Illuminate\Support\Collection as LaravelCollection; +use InvalidArgumentException; use Override; /** @@ -201,4 +202,17 @@ public function unwrapped(): array return OutputCollectionPipeline::process($output)->toArray(); } + + /** + * @param array{items: array} $array + */ + public static function __set_state(array $array): object + { + if (!isset($array['items'])) { + throw new InvalidArgumentException('Invalid state array for ' . static::class); + } + + // @phpstan-ignore-next-line new.static + return new static($array['items']); + } } diff --git a/tests/Feature/CollectionTest.php b/tests/Feature/CollectionTest.php index 53fa7fe..28fa3d1 100644 --- a/tests/Feature/CollectionTest.php +++ b/tests/Feature/CollectionTest.php @@ -118,3 +118,26 @@ $collection = WrappedCollection::make(['foo' => 'bar']); expect($collection->unwrapped())->toBe(['foo' => 'bar']); }); + +test('it can be var_exported', function () { + $collection = Collection::make(['foo' => 'bar']); + + $exported = var_export($collection, true); + + expect($exported)->toBe( + << + array ( + 'foo' => 'bar', + ), + 'escapeWhenCastingToString' => false, + )) + EOS + ); + + $imported = eval('return ' . $exported . ';'); + + expect($imported)->toBeInstanceOf(Collection::class) + ->and($imported->toArray())->toBe($collection->toArray()); +});