Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0ed6766

Browse files
[PropertyInfo] Make ReflectionExtractor correctly extract nullability
ReflectionExtractor was always returning isNullable: false if property had default value. After PHP 7.4 we can get isNullable from the typehint
1 parent 2a3f912 commit 0ed6766

File tree

3 files changed

+11
-1
lines changed

3 files changed

+11
-1
lines changed

src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -314,8 +314,16 @@ private function extractFromConstructor(string $class, string $property): ?array
314314

315315
private function extractFromDefaultValue(string $class, string $property): ?array
316316
{
317+
$isNullable = false;
318+
317319
try {
318320
$reflectionClass = new \ReflectionClass($class);
321+
322+
if (\PHP_VERSION_ID >= 70400) {
323+
$type = $reflectionClass->getProperty($property)->getType();
324+
325+
$isNullable = null !== $type && $type->allowsNull();
326+
}
319327
} catch (\ReflectionException $e) {
320328
return null;
321329
}
@@ -328,7 +336,7 @@ private function extractFromDefaultValue(string $class, string $property): ?arra
328336

329337
$type = \gettype($defaultValue);
330338

331-
return [new Type(static::MAP_TYPES[$type] ?? $type)];
339+
return [new Type(static::MAP_TYPES[$type] ?? $type, $isNullable)];
332340
}
333341

334342
private function extractFromReflectionType(\ReflectionType $reflectionType, \ReflectionClass $declaringClass): array

src/Symfony/Component/PropertyInfo/Tests/Extractor/ReflectionExtractorTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,5 +414,6 @@ public function testTypedProperties()
414414
$this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, Dummy::class)], $this->extractor->getTypes(Php74Dummy::class, 'dummy'));
415415
$this->assertEquals([new Type(Type::BUILTIN_TYPE_BOOL, true)], $this->extractor->getTypes(Php74Dummy::class, 'nullableBoolProp'));
416416
$this->assertEquals([new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING))], $this->extractor->getTypes(Php74Dummy::class, 'stringCollection'));
417+
$this->assertEquals([new Type(Type::BUILTIN_TYPE_INT, true)], $this->extractor->getTypes(Php74Dummy::class, 'nullableWithDefault'));
417418
}
418419
}

src/Symfony/Component/PropertyInfo/Tests/Fixtures/Php74Dummy.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ class Php74Dummy
2020
private ?bool $nullableBoolProp;
2121
/** @var string[] */
2222
private array $stringCollection;
23+
private ?int $nullableWithDefault = 1;
2324

2425
public function addStringCollection(string $string): void
2526
{

0 commit comments

Comments
 (0)