From 4cd52a0b46ba7c851debcc8e80696160959ebe16 Mon Sep 17 00:00:00 2001 From: Grundik Date: Tue, 16 May 2023 22:12:57 +0300 Subject: [PATCH] Nullable flag on constructor property promotion, closes #183 Signed-off-by: Grundik --- src/Generator/ParameterGenerator.php | 9 +++++++ src/Generator/PromotedParameterGenerator.php | 6 ++++- src/Generator/TypeGenerator.php | 9 +++++++ .../PromotedParameterGeneratorTest.php | 25 +++++++++++++++++++ .../TestAsset/ClassWithPromotedProperties.php | 18 +++++++++++++ 5 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 test/Generator/PromotedParameterGeneratorTest.php create mode 100644 test/TestAsset/ClassWithPromotedProperties.php diff --git a/src/Generator/ParameterGenerator.php b/src/Generator/ParameterGenerator.php index 48434ab4..496d125b 100644 --- a/src/Generator/ParameterGenerator.php +++ b/src/Generator/ParameterGenerator.php @@ -167,6 +167,15 @@ public function getType() : null; } + /** + * @return ?TypeGenerator + * @psalm-pure + */ + public function getTypeObject() + { + return $this->type; + } + /** * @param string $name * @return ParameterGenerator diff --git a/src/Generator/PromotedParameterGenerator.php b/src/Generator/PromotedParameterGenerator.php index 56cd02cf..48855c12 100644 --- a/src/Generator/PromotedParameterGenerator.php +++ b/src/Generator/PromotedParameterGenerator.php @@ -87,9 +87,13 @@ public static function fromParameterGeneratorWithVisibility(ParameterGenerator $ ); } + if ($generator->getTypeObject() && $generator->getTypeObject()->getNullable()) { + $typeString = '?' . $type; + } + return new self( $name, - $type, + $typeString, $visibility, $generator->getPosition(), $generator->getPassedByReference() diff --git a/src/Generator/TypeGenerator.php b/src/Generator/TypeGenerator.php index 0d7fc532..d30284fa 100644 --- a/src/Generator/TypeGenerator.php +++ b/src/Generator/TypeGenerator.php @@ -140,6 +140,15 @@ public function __toString(): string return $this->type->toString(); } + /** + * @return bool Nullable flag + * @psalm-pure + */ + public function getNullable() + { + return $this->nullable; + } + /** * @return bool[]|string[] ordered tuple, first key represents whether the type is nullable, second is the * trimmed string diff --git a/test/Generator/PromotedParameterGeneratorTest.php b/test/Generator/PromotedParameterGeneratorTest.php new file mode 100644 index 00000000..7d2a9eca --- /dev/null +++ b/test/Generator/PromotedParameterGeneratorTest.php @@ -0,0 +1,25 @@ +assertSame('protected ?int $nullable', $generator->generate()); + } +} diff --git a/test/TestAsset/ClassWithPromotedProperties.php b/test/TestAsset/ClassWithPromotedProperties.php new file mode 100644 index 00000000..4d932d3c --- /dev/null +++ b/test/TestAsset/ClassWithPromotedProperties.php @@ -0,0 +1,18 @@ +