Skip to content

Commit

Permalink
MissingClassConstantTypehintRule should not apply to native types
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Jan 22, 2024
1 parent 8d4ea60 commit 6363932
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/Rules/Constants/MissingClassConstantTypehintRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ public function processNode(Node $node, Scope $scope): array
private function processSingleConstant(ClassReflection $classReflection, string $constantName): array
{
$constantReflection = $classReflection->getConstant($constantName);
$constantType = $constantReflection->getValueType();
$constantType = $constantReflection->getPhpDocType();
if ($constantType === null) {
return [];
}

$errors = [];
foreach ($this->missingTypehintCheck->getIterableTypesWithMissingValueTypehint($constantType) as $iterableType) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,24 @@ public function testBug8957(): void
$this->analyse([__DIR__ . '/data/bug-8957.php'], []);
}

public function testRuleShouldNotApplyToNativeTypes(): void
{
if (PHP_VERSION_ID < 80300) {
$this->markTestSkipped('This test needs PHP 8.3');
}

$this->analyse([__DIR__ . '/data/class-constant-native-type.php'], [
[
'Constant ClassConstantNativeTypeForMissingTypehintRule\Foo::B type has no value type specified in iterable type array.',
19,
'See: https://phpstan.org/blog/solving-phpstan-no-value-type-specified-in-iterable-type',
],
[
'Constant ClassConstantNativeTypeForMissingTypehintRule\Foo::D with generic class ClassConstantNativeTypeForMissingTypehintRule\Bar does not specify its types: T',
24,
'You can turn this off by setting <fg=cyan>checkGenericClassInNonGenericObjectType: false</> in your <fg=cyan>%configurationFile%</>.',
],
]);
}

}
25 changes: 25 additions & 0 deletions tests/PHPStan/Rules/Constants/data/class-constant-native-type.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php // lint >= 8.3

namespace ClassConstantNativeTypeForMissingTypehintRule;

/** @template T */
class Bar
{

}

const ConstantWithObjectInstanceForNativeType = new Bar();

class Foo
{

public const array A = [];

/** @var array */
public const array B = [];

public const Bar C = ConstantWithObjectInstanceForNativeType;

/** @var Bar */
public const Bar D = ConstantWithObjectInstanceForNativeType;
}

0 comments on commit 6363932

Please sign in to comment.