From c0195a14899fb02fe774455a02787530dc833fda Mon Sep 17 00:00:00 2001 From: recca0120 Date: Fri, 29 Apr 2022 15:03:42 +0800 Subject: [PATCH] get string when backed enum type is string --- src/Processors/ExpandEnums.php | 6 ++-- tests/Fixtures/PHP/StatusEnumStringBacked.php | 13 ++++++++ tests/Processors/ExpandEnumsTest.php | 32 ++++++++++++++++--- 3 files changed, 44 insertions(+), 7 deletions(-) create mode 100644 tests/Fixtures/PHP/StatusEnumStringBacked.php diff --git a/src/Processors/ExpandEnums.php b/src/Processors/ExpandEnums.php index 22f0a0d33..f3d826323 100644 --- a/src/Processors/ExpandEnums.php +++ b/src/Processors/ExpandEnums.php @@ -33,13 +33,13 @@ public function __invoke(Analysis $analysis) $source = $schema->_context->enum; $re = new \ReflectionEnum($schema->_context->fullyQualifiedName($source)); $schema->schema = !Generator::isDefault($schema->schema) ? $schema->schema : $re->getShortName(); - $schema->enum = array_map(function ($case) { - return $case->name; - }, $re->getCases()); $type = 'string'; if ($re->isBacked() && ($backingType = $re->getBackingType()) && method_exists($backingType, 'getName')) { $type = !Generator::isDefault($schema->type) ? $schema->type : $backingType->getName(); } + $schema->enum = array_map(function ($case) use ($re, $type) { + return $re->isBacked() && $type === 'string' ? $case->getBackingValue() : $case->name; + }, $re->getCases()); Util::mapNativeType($schema, $type); } } diff --git a/tests/Fixtures/PHP/StatusEnumStringBacked.php b/tests/Fixtures/PHP/StatusEnumStringBacked.php new file mode 100644 index 000000000..bf809d1d8 --- /dev/null +++ b/tests/Fixtures/PHP/StatusEnumStringBacked.php @@ -0,0 +1,13 @@ +getAnalyzer() instanceof TokenAnalyser) { $this->markTestSkipped(); } } public function testExpandUnitEnum(): void { - $analysis = $this->analysisFromFixtures(['PHP/StatusEnum.php']); + $analysis = $this->analysisFromFixtures(['PHP/StatusEnum.php'], [], $this->getAnalyzer()); $analysis->process([new ExpandEnums()]); $schema = $analysis->getSchemaForSource(StatusEnum::class); self::assertEquals(['DRAFT', 'PUBLISHED', 'ARCHIVED'], $schema->enum); } -} \ No newline at end of file + + public function testExpandBackedEnum(): void + { + $analysis = $this->analysisFromFixtures(['PHP/StatusEnumBacked.php'], [], $this->getAnalyzer()); + $analysis->process([new ExpandEnums()]); + $schema = $analysis->getSchemaForSource(StatusEnumBacked::class); + + self::assertEquals(['DRAFT', 'PUBLISHED', 'ARCHIVED'], $schema->enum); + } + + public function testExpandBackedStringEnum(): void + { + $analysis = $this->analysisFromFixtures(['PHP/StatusEnumStringBacked.php'], [], $this->getAnalyzer()); + $analysis->process([new ExpandEnums()]); + $schema = $analysis->getSchemaForSource(StatusEnumStringBacked::class); + + self::assertEquals(['draft', 'published', 'archived'], $schema->enum); + } +}