Skip to content

Commit

Permalink
feat: Add support for var_export() to Collection
Browse files Browse the repository at this point in the history
  • Loading branch information
dshafik committed Feb 4, 2025
1 parent d7f0f33 commit 6b101a1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Bag/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Bag\Pipelines\OutputCollectionPipeline;
use Bag\Pipelines\Values\CollectionOutput;
use Illuminate\Support\Collection as LaravelCollection;
use InvalidArgumentException;
use Override;

/**
Expand Down Expand Up @@ -201,4 +202,17 @@ public function unwrapped(): array

return OutputCollectionPipeline::process($output)->toArray();
}

/**
* @param array{items: array<mixed>} $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']);
}
}
23 changes: 23 additions & 0 deletions tests/Feature/CollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<<<EOS
\Bag\Collection::__set_state(array(
'items' =>
array (
'foo' => 'bar',
),
'escapeWhenCastingToString' => false,
))
EOS
);

$imported = eval('return ' . $exported . ';');

expect($imported)->toBeInstanceOf(Collection::class)
->and($imported->toArray())->toBe($collection->toArray());
});

0 comments on commit 6b101a1

Please sign in to comment.