From 69382e271e1d2c21aa1922d455819d178608f803 Mon Sep 17 00:00:00 2001 From: Fan2Shrek Date: Wed, 31 Jul 2024 18:59:09 +0200 Subject: [PATCH] Fix 1580 - Mulitiple and Nullable enum --- src/Util/ClassSourceManipulator.php | 20 +++++++++++++++----- tests/Maker/MakeEntityTest.php | 23 +++++++++++++++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/src/Util/ClassSourceManipulator.php b/src/Util/ClassSourceManipulator.php index 51593f5dc..25b57bdbb 100644 --- a/src/Util/ClassSourceManipulator.php +++ b/src/Util/ClassSourceManipulator.php @@ -121,13 +121,23 @@ public function addEntityField(ClassProperty $mapping): void $defaultValue = null; $commentLines = []; - if ('array' === $typeHint && !$nullable) { - $defaultValue = new Node\Expr\Array_([], ['kind' => Node\Expr\Array_::KIND_SHORT]); - if (null !== $mapping->enumType) { + + if (null !== $mapping->enumType) { + if ('array' === $typeHint) { + // still need to add the use statement + $this->addUseStatementIfNecessary($mapping->enumType); + $commentLines = [\sprintf('@return %s[]', Str::getShortClassName($mapping->enumType))]; + if ($nullable) { + $commentLines[0] = \sprintf('%s|null', $commentLines[0]); + } else { + $defaultValue = new Node\Expr\Array_([], ['kind' => Node\Expr\Array_::KIND_SHORT]); + } + } else { + $typeHint = $this->addUseStatementIfNecessary($mapping->enumType); } - } elseif (null !== $mapping->enumType) { - $typeHint = $this->addUseStatementIfNecessary($mapping->enumType); + } elseif ('array' === $typeHint && !$nullable) { + $defaultValue = new Node\Expr\Array_([], ['kind' => Node\Expr\Array_::KIND_SHORT]); } elseif ($typeHint && '\\' === $typeHint[0] && false !== strpos($typeHint, '\\', 1)) { $typeHint = $this->addUseStatementIfNecessary(substr($typeHint, 1)); } diff --git a/tests/Maker/MakeEntityTest.php b/tests/Maker/MakeEntityTest.php index 8bb34db48..4403a53c2 100644 --- a/tests/Maker/MakeEntityTest.php +++ b/tests/Maker/MakeEntityTest.php @@ -735,6 +735,29 @@ public function getTestDetails(): \Generator $this->runEntityTest($runner); }), ]; + + yield 'it_creates_a_new_class_with_enum_field_multiple_and_nullable' => [$this->createMakeEntityTest() + ->run(function (MakerTestRunner $runner) { + $this->copyEntity($runner, 'Enum/Role-basic.php'); + + $runner->runMaker([ + // entity class name + 'User', + // add additional field + 'role', + 'enum', + 'App\\Entity\\Enum\\Role', + // multiple + 'y', + // nullable + 'y', + // finish adding fields + '', + ]); + + $this->runEntityTest($runner); + }), + ]; } /** @param array $data */