Skip to content

Commit

Permalink
Check default property value against native type
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Jun 3, 2020
1 parent 5d76184 commit 4329b07
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 4 deletions.
2 changes: 2 additions & 0 deletions build.xml
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@
<arg path="tests/PHPStan/Rules/Classes/data/interface-extends-error.php"/>
<arg value="--exclude"/>
<arg path="tests/PHPStan/Rules/Classes/data/trait-use-error.php"/>
<arg value="--exclude"/>
<arg path="tests/PHPStan/Rules/Properties/data/default-value-for-native-property-type.php"/>
<arg path="src" />
<arg path="tests" />
<arg path="compiler/src" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use PHPStan\Analyser\Scope;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Rules\RuleLevelHelper;
use PHPStan\Type\MixedType;
use PHPStan\Type\VerbosityLevel;

/**
Expand Down Expand Up @@ -41,12 +42,13 @@ public function processNode(Node $node, Scope $scope): array
continue;
}

if ($property->default instanceof Node\Expr\ConstFetch && (string) $property->default->name === 'null') {
continue;
}

$propertyReflection = $classReflection->getNativeProperty($property->name->name);
$propertyType = $propertyReflection->getWritableType();
if ($propertyReflection->getNativeType() instanceof MixedType) {
if ($property->default instanceof Node\Expr\ConstFetch && (string) $property->default->name === 'null') {
continue;
}
}
$defaultValueType = $scope->getType($property->default);
if ($this->ruleLevelHelper->accepts($propertyType, $defaultValueType, $scope->isDeclareStrictTypes())) {
continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,17 @@ public function testDefaultValueTypesAssignedToProperties(): void
]);
}

public function testDefaultValueForNativePropertyType(): void
{
if (!self::$useStaticReflectionProvider) {
$this->markTestSkipped('Test requires static reflection.');
}
$this->analyse([__DIR__ . '/data/default-value-for-native-property-type.php'], [
[
'Property DefaultValueForNativePropertyType\Foo::$foo (DateTime) does not accept default value of type null.',
8,
],
]);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace DefaultValueForNativePropertyType;

class Foo
{

private \DateTime $foo = null;

}

0 comments on commit 4329b07

Please sign in to comment.