Skip to content

Commit 0531bad

Browse files
committed
Nullable flag on constructor property promotion, closes #183
Signed-off-by: Grundik <[email protected]>
1 parent 169123b commit 0531bad

File tree

5 files changed

+67
-0
lines changed

5 files changed

+67
-0
lines changed

src/Generator/ParameterGenerator.php

+8
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,14 @@ public function getType()
167167
: null;
168168
}
169169

170+
/**
171+
* @return ?TypeGenerator
172+
*/
173+
public function getTypeObject()
174+
{
175+
return $this->type;
176+
}
177+
170178
/**
171179
* @param string $name
172180
* @return ParameterGenerator

src/Generator/PromotedParameterGenerator.php

+8
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,14 @@ public static function fromParameterGeneratorWithVisibility(ParameterGenerator $
8787
);
8888
}
8989

90+
if (
91+
null !== $type
92+
&& ($typeObject = $generator->getTypeObject())
93+
&& $typeObject->getNullable()
94+
) {
95+
$type = '?' . $type;
96+
}
97+
9098
return new self(
9199
$name,
92100
$type,

src/Generator/TypeGenerator.php

+8
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,14 @@ public function __toString(): string
140140
return $this->type->toString();
141141
}
142142

143+
/**
144+
* @return bool Nullable flag
145+
*/
146+
public function getNullable()
147+
{
148+
return $this->nullable;
149+
}
150+
143151
/**
144152
* @return bool[]|string[] ordered tuple, first key represents whether the type is nullable, second is the
145153
* trimmed string
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace LaminasTest\Code\Generator;
6+
7+
use Laminas\Code\Generator\PromotedParameterGenerator;
8+
use Laminas\Code\Reflection\ParameterReflection;
9+
use LaminasTest\Code\TestAsset\ClassWithPromotedProperties;
10+
use PHPUnit\Framework\Attributes\Group;
11+
use PHPUnit\Framework\TestCase;
12+
13+
#[Group('Laminas_Code_Generator')]
14+
#[Group('Laminas_Code_Generator_Php')]
15+
class PromotedParameterGeneratorTest extends TestCase
16+
{
17+
public function testNullablePromotedProperty(): void
18+
{
19+
$parameterReflection = new ParameterReflection([ClassWithPromotedProperties::class, '__construct'], 0);
20+
21+
$generator = PromotedParameterGenerator::fromReflection($parameterReflection);
22+
23+
$this->assertSame('protected ?int $nullable', $generator->generate());
24+
}
25+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace LaminasTest\Code\TestAsset;
6+
7+
/**
8+
* Class with a promoted constructor properties
9+
*
10+
* @license MIT
11+
*/
12+
class ClassWithPromotedProperties
13+
{
14+
public function __construct(
15+
protected ?int $nullable
16+
) {
17+
}
18+
}

0 commit comments

Comments
 (0)