From 0bf1ce8e55fe0d479401de707332cb3d96ee9617 Mon Sep 17 00:00:00 2001 From: Sandro Keil Date: Thu, 10 Dec 2020 09:31:33 +0100 Subject: [PATCH] Use nullable also if property is not required --- src/ClassGenerator.php | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/ClassGenerator.php b/src/ClassGenerator.php index 327928a..207e3c7 100644 --- a/src/ClassGenerator.php +++ b/src/ClassGenerator.php @@ -122,7 +122,7 @@ public function generateClasses( $classBuilder->addProperty( ClassPropertyBuilder::fromScratch( $propertyPropertyName, - $propertyType->isNullable() ? ('?' . $propertyClassName) : $propertyClassName + $this->determinePropertyType($propertyType, $propertyClassName) ) ); break; @@ -140,7 +140,7 @@ public function generateClasses( $classBuilder->addProperty( ClassPropertyBuilder::fromScratch( $propertyPropertyName, - $propertyType->isNullable() ? ('?' . $propertyClassName) : $propertyClassName + $this->determinePropertyType($propertyType, $propertyClassName) ) ); $classBuilder->addNamespaceImport($classNamespace . '\\' . $propertyClassName); @@ -153,7 +153,7 @@ public function generateClasses( $classBuilder->addProperty( ClassPropertyBuilder::fromScratch( $propertyPropertyName, - $propertyType->isNullable() ? ('?' . $propertyClassName) : $propertyClassName + $this->determinePropertyType($propertyType, $propertyClassName) ) ); break; @@ -329,4 +329,11 @@ private function isValueObject(ClassBuilder $classBuilder): bool || $classBuilder->hasMethod('toFloat') || $classBuilder->hasMethod('toBool'); } + + private function determinePropertyType(TypeDefinition $typeDefinition, string $className): string + { + return ($typeDefinition->isRequired() === false || $typeDefinition->isNullable() === true) + ? ('?' . $className) + : $className; + } }