Skip to content
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

Restore enum instance from var_export() #252

Merged
merged 1 commit into from
Mar 11, 2022
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased](https://github.com/BenSampo/laravel-enum/compare/v5.1.0...master)

### Added

- Restore enum instance from `var_export()`

## [5.1.0](https://github.com/BenSampo/laravel-enum/compare/v5.0.0...v5.1.0) - 2022-02-09

### Added
Expand Down
11 changes: 11 additions & 0 deletions src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,17 @@ public function __construct($enumValue)
$this->description = static::getDescription($enumValue);
}

/**
* Restores an enum instance exported by var_export().
*
* @param array{value: mixed, key: string, description: string} $enum
* @return static
*/
public static function __set_state(array $enum): static
{
return new static($enum['value']);
}

/**
* Make a new instance from an enum value.
*
Expand Down
19 changes: 19 additions & 0 deletions tests/VarExportTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace BenSampo\Enum\Tests;

use PHPUnit\Framework\TestCase;
use BenSampo\Enum\Tests\Enums\UserType;

class VarExportTest extends TestCase
{
public function test_var_export()
{
$admin = UserType::Administrator();

$exported = var_export($admin, true);
$restored = eval("return {$exported};");

$this->assertSame($admin->value, $restored->value);
}
}