From 078219f8f798d287fec27f315da3d727f6b579b8 Mon Sep 17 00:00:00 2001 From: Shish Date: Mon, 2 Dec 2024 17:11:43 +0000 Subject: [PATCH] Detect nullable-default parameters and generate appropriate outputs (#486) --- generator/src/Parameter.php | 12 ++++++++++-- generator/src/WritePhpFunction.php | 18 +++++++++++++++++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/generator/src/Parameter.php b/generator/src/Parameter.php index 27c6e7e4..5b89f78e 100644 --- a/generator/src/Parameter.php +++ b/generator/src/Parameter.php @@ -81,7 +81,15 @@ public function isVariadic(): bool public function isNullable(): bool { - return $this->type->isNullable(); + if ($this->type->isNullable()) { + return true; + } + + if ($this->getDefaultValue() === "null") { + return true; + } + + return $this->getDefaultValue() === "NULL"; } /* @@ -94,7 +102,7 @@ public function getInitializer(): string public function hasDefaultValue(): bool { - return isset($this->parameter->initializer); + return property_exists($this->parameter, 'initializer') && $this->parameter->initializer !== null; } public function getDefaultValue(): ?string diff --git a/generator/src/WritePhpFunction.php b/generator/src/WritePhpFunction.php index 8f4582b2..ca892539 100644 --- a/generator/src/WritePhpFunction.php +++ b/generator/src/WritePhpFunction.php @@ -137,9 +137,21 @@ private function displayParamsWithType(array $params): string $optDetected = false; foreach ($params as $param) { - $paramAsString = $param->getSignatureType(); + $paramAsString = ''; + $typeDetected = false; + + // parameters can not have type void + if ($param->getSignatureType() !== 'void') { + $paramAsString = $param->getSignatureType(); + } + if ($paramAsString !== '') { $paramAsString .= ' '; + if ($param->isNullable() && $paramAsString[0] !== "?") { + $paramAsString = "?" . $paramAsString; + } + + $typeDetected = true; } $paramName = $param->getParameterName(); @@ -161,6 +173,10 @@ private function displayParamsWithType(array $params): string $paramAsString .= ' = '.$this->defaultValueToString($defaultValue); } elseif ($optDetected && !$param->isVariadic()) { $paramAsString .= ' = null'; + + if ($typeDetected && $paramAsString[0] !== "?") { + $paramAsString = "?" . $paramAsString; + } } $paramsAsString[] = $paramAsString; }