Skip to content

Commit

Permalink
feat: Add support for var_export()
Browse files Browse the repository at this point in the history
  • Loading branch information
dshafik committed Feb 4, 2025
1 parent c887cba commit 785e242
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/Bag/Bag.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,12 @@ public static function rules(): array
{
return [];
}

/**
* @param array<mixed> $array
*/
public static function __set_state(array $array): static
{
return static::from($array);
}
}
24 changes: 24 additions & 0 deletions tests/Feature/BagTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -216,3 +216,27 @@
->and($value->age)->toBe('40')
->and($value->email)->toBe(false);
});

test('it can be var_exported', function () {
$value = TestBag::from('Davey Shafik', 40, '[email protected]');

$exported = var_export($value, true);

expect($exported)->toBe('\Tests\Fixtures\Values\TestBag::__set_state(array(' . PHP_EOL . ' \'name\' => \'Davey Shafik\',' . PHP_EOL . ' \'age\' => 40,' . PHP_EOL . ' \'email\' => \'[email protected]\',' . PHP_EOL . '))');

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

expect($imported)->toBeInstanceOf(TestBag::class)
->and($imported->toArray())->toBe($value->toArray());
});

test('it can be serialized and unserialized', function () {
$value = TestBag::from('Davey Shafik', 40, '[email protected]');

$serialized = serialize($value);
$unserialized = unserialize($serialized);

/** @var TestBag $unserialized */
expect($unserialized)->toBeInstanceOf(TestBag::class)
->and($unserialized->toArray())->toBe($value->toArray());
});

0 comments on commit 785e242

Please sign in to comment.