[VarExporter] Add support of PHP enumerations

This commit is contained in:
Alexandre Daubois 2021-04-30 17:29:27 +02:00 committed by Nicolas Grekas
parent c8cc4c3ee3
commit 4b0f2997a5
5 changed files with 21 additions and 3 deletions

View File

@ -62,7 +62,7 @@ class Exporter
$value = self::prepare($value, $objectsPool, $refsPool, $objectsCount, $valueIsStatic);
}
goto handle_value;
} elseif (!\is_object($value) && !$value instanceof \__PHP_Incomplete_Class) {
} elseif (!\is_object($value) && !$value instanceof \__PHP_Incomplete_Class || $value instanceof \UnitEnum) {
goto handle_value;
}
@ -190,7 +190,7 @@ class Exporter
public static function export($value, $indent = '')
{
switch (true) {
case \is_int($value) || \is_float($value): return var_export($value, true);
case \is_int($value) || \is_float($value) || $value instanceof \UnitEnum: return var_export($value, true);
case [] === $value: return '[]';
case false === $value: return 'false';
case true === $value: return 'true';

View File

@ -0,0 +1,8 @@
<?php
namespace Symfony\Component\VarExporter\Tests\Fixtures;
enum FooUnitEnum
{
case Bar;
}

View File

@ -0,0 +1,5 @@
<?php
return [
Symfony\Component\VarExporter\Tests\Fixtures\FooUnitEnum::Bar,
];

View File

@ -16,6 +16,7 @@ use Symfony\Component\VarDumper\Test\VarDumperTestTrait;
use Symfony\Component\VarExporter\Exception\ClassNotFoundException;
use Symfony\Component\VarExporter\Exception\NotInstantiableTypeException;
use Symfony\Component\VarExporter\Internal\Registry;
use Symfony\Component\VarExporter\Tests\Fixtures\FooUnitEnum;
use Symfony\Component\VarExporter\VarExporter;
class VarExporterTest extends TestCase
@ -209,6 +210,10 @@ class VarExporterTest extends TestCase
yield ['private-constructor', PrivateConstructor::create('bar')];
yield ['php74-serializable', new Php74Serializable()];
if (\PHP_VERSION_ID >= 80100) {
yield ['unit-enum', [FooUnitEnum::Bar], true];
}
}
}

View File

@ -43,7 +43,7 @@ final class VarExporter
{
$isStaticValue = true;
if (!\is_object($value) && !(\is_array($value) && $value) && !$value instanceof \__PHP_Incomplete_Class && !\is_resource($value)) {
if (!\is_object($value) && !(\is_array($value) && $value) && !$value instanceof \__PHP_Incomplete_Class && !\is_resource($value) || $value instanceof \UnitEnum) {
return Exporter::export($value);
}