bug #41072 [VarExporter] Add support of PHP enumerations (alexandre-daubois)

This PR was merged into the 4.4 branch.

Discussion
----------

[VarExporter] Add support of PHP enumerations

| Q             | A
| ------------- | ---
| Branch?       | 4.4
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       | Fix #40237
| License       | MIT
| Doc PR        | _none_

Commits
-------

4b0f2997a5 [VarExporter] Add support of PHP enumerations
This commit is contained in:
Nicolas Grekas 2021-05-06 21:18:04 +02:00
commit e51e651c4a
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);
}