From 0e60e7d5bb3575560c8920ad5842e1ee3d31b922 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20=C5=A0ustek?= Date: Wed, 13 Nov 2024 14:50:57 +0100 Subject: [PATCH] Add support for enum to Utils::stringifyValue in order to support enum as default value of class property --- composer.json | 5 +++++ src/Utils.php | 4 ++++ tests/Fixtures/BasicEnum.php | 9 +++++++++ tests/Fixtures/StringBackedEnum.php | 9 +++++++++ tests/UtilsTest.php | 18 ++++++++++++++++++ 5 files changed, 45 insertions(+) create mode 100644 tests/Fixtures/BasicEnum.php create mode 100644 tests/Fixtures/StringBackedEnum.php diff --git a/composer.json b/composer.json index 40152dc..7f7f03d 100644 --- a/composer.json +++ b/composer.json @@ -19,6 +19,11 @@ "Murtukov\\PHPCodeGenerator\\": "src/" } }, + "autoload-dev": { + "psr-4": { + "Tests\\": "tests/" + } + }, "require-dev": { "phpstan/phpstan": "^1.12.4", "phpunit/phpunit": "^10", diff --git a/src/Utils.php b/src/Utils.php index 39f3e2f..c3a477c 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -96,6 +96,10 @@ private static function stringifyValue(mixed $value, bool $topLevel = false): st case 'object': if (!$value instanceof GeneratorInterface) { + if (enum_exists($value::class)) { + return '\\'.$value::class.'::'.$value->name; + } + try { $result = json_encode($value->__toString()); diff --git a/tests/Fixtures/BasicEnum.php b/tests/Fixtures/BasicEnum.php new file mode 100644 index 0000000..1d11d0b --- /dev/null +++ b/tests/Fixtures/BasicEnum.php @@ -0,0 +1,9 @@ +assertEquals('\\Tests\\Fixtures\\BasicEnum::ONE', Utils::stringify(BasicEnum::ONE)); + } + + /** + * @test + */ + public function stringifyBackedEnum(): void + { + $this->assertEquals('\\Tests\\Fixtures\\StringBackedEnum::ONE', Utils::stringify(StringBackedEnum::ONE)); + } + /** * @test */