Skip to content

Commit

Permalink
Nullable flag on constructor property promotion, closes #183
Browse files Browse the repository at this point in the history
Signed-off-by: Grundik <[email protected]>
  • Loading branch information
Grundik committed May 16, 2023
1 parent 169123b commit f15c294
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/Generator/ParameterGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,14 @@ public function getType()
: null;
}

/**
* @return bool
*/
public function getNullable()
{
return $this->type && $this->type->getNullable();
}

/**
* @param string $name
* @return ParameterGenerator
Expand Down
4 changes: 4 additions & 0 deletions src/Generator/PromotedParameterGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ public static function fromParameterGeneratorWithVisibility(ParameterGenerator $
);
}

if ($generator->getNullable()) {
$type = '?' . $type;
}

return new self(
$name,
$type,
Expand Down
8 changes: 8 additions & 0 deletions src/Generator/TypeGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,14 @@ public function __toString(): string
return $this->type->toString();
}

/**
* @return bool Nullable flag
*/
public function getNullable()
{
return $this->nullable;
}

/**
* @return bool[]|string[] ordered tuple, first key represents whether the type is nullable, second is the
* trimmed string
Expand Down
25 changes: 25 additions & 0 deletions test/Generator/PromotedParameterGeneratorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

namespace LaminasTest\Code\Generator;

use Laminas\Code\Generator\PromotedParameterGenerator;
use Laminas\Code\Reflection\ParameterReflection;
use LaminasTest\Code\TestAsset\ClassWithPromotedProperties;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\TestCase;

#[Group('Laminas_Code_Generator')]
#[Group('Laminas_Code_Generator_Php')]
class PromotedParameterGeneratorTest extends TestCase
{
public function testNullablePromotedProperty(): void
{
$parameterReflection = new ParameterReflection([ClassWithPromotedProperties::class, '__construct'], 0);

$generator = PromotedParameterGenerator::fromReflection($parameterReflection);

$this->assertSame('protected ?int $nullable', $generator->generate());
}
}
18 changes: 18 additions & 0 deletions test/TestAsset/ClassWithPromotedProperties.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace LaminasTest\Code\TestAsset;

/**
* Class with a promoted constructor properties
*
* @license MIT
*/
class ClassWithPromotedProperties
{
public function __construct(
protected ?int $nullable
) {
}
}

0 comments on commit f15c294

Please sign in to comment.