diff --git a/src/Generator/ValueGenerator.php b/src/Generator/ValueGenerator.php index 56251d11..6f93070f 100644 --- a/src/Generator/ValueGenerator.php +++ b/src/Generator/ValueGenerator.php @@ -5,6 +5,7 @@ use ArrayObject as SplArrayObject; use Laminas\Code\Exception\InvalidArgumentException; use Laminas\Stdlib\ArrayObject as StdlibArrayObject; +use UnitEnum; use function addcslashes; use function array_keys; @@ -43,6 +44,7 @@ class ValueGenerator extends AbstractGenerator public const TYPE_ARRAY_LONG = 'array_long'; public const TYPE_CONSTANT = 'constant'; public const TYPE_NULL = 'null'; + public const TYPE_ENUM = 'enum'; public const TYPE_OBJECT = 'object'; public const TYPE_OTHER = 'other'; /**#@-*/ @@ -264,6 +266,7 @@ protected function getValidatedType($type) self::TYPE_ARRAY_LONG, self::TYPE_CONSTANT, self::TYPE_NULL, + self::TYPE_ENUM, self::TYPE_OBJECT, self::TYPE_OTHER, ]; @@ -304,6 +307,10 @@ public function getAutoDeterminedType($value) case 'NULL': return self::TYPE_NULL; case 'object': + // enums are typed as objects, so this fall through is intentional + if ($value instanceof UnitEnum) { + return self::TYPE_ENUM; + } case 'resource': case 'unknown type': default: @@ -418,6 +425,13 @@ public function generate() } $output .= $endArray; break; + case self::TYPE_ENUM: + if (!is_object($value)) { + throw new Exception\RuntimeException('Value is not an object.'); + } + + $output = sprintf('%s::%s', get_class($value), (string) $value->name); + break; case self::TYPE_OTHER: default: throw new Exception\RuntimeException(sprintf( diff --git a/test/Generator/TestAsset/TestEnum.php b/test/Generator/TestAsset/TestEnum.php new file mode 100644 index 00000000..c376e87f --- /dev/null +++ b/test/Generator/TestAsset/TestEnum.php @@ -0,0 +1,9 @@ +generate(), $valueGenerator2->generate()); } + /** @requires PHP >= 8.1 */ + public function testPropertyDefaultValueCanHandleEnums(): void + { + $valueGenerator1 = new ValueGenerator( + TestEnum::Test1, + ValueGenerator::TYPE_AUTO, + ValueGenerator::OUTPUT_MULTIPLE_LINE + ); + + $valueGenerator2 = new ValueGenerator( + TestEnum::Test2, + ValueGenerator::TYPE_ENUM, + ValueGenerator::OUTPUT_MULTIPLE_LINE + ); + + $valueGenerator1->initEnvironmentConstants(); + $valueGenerator2->initEnvironmentConstants(); + + self::assertNotEquals($valueGenerator1->generate(), $valueGenerator2->generate()); + self::assertEquals(sprintf('%s::%s', TestEnum::class, 'Test1'), $valueGenerator1->generate()); + self::assertEquals(sprintf('%s::%s', TestEnum::class, 'Test2'), $valueGenerator2->generate()); + } + /** * @dataProvider simpleArray * @param string $type