Skip to content

Commit c92066d

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

File tree

5 files changed

+63
-0
lines changed

5 files changed

+63
-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 bool
172+
*/
173+
public function getNullable()
174+
{
175+
return $this->type && $this->type->getNullable();
176+
}
177+
170178
/**
171179
* @param string $name
172180
* @return ParameterGenerator

src/Generator/PromotedParameterGenerator.php

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

90+
if ($type && $generator->getNullable()) {
91+
$type = '?' . $type;
92+
}
93+
9094
return new self(
9195
$name,
9296
$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)