Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions src/Type/ObjectType.php
Original file line number Diff line number Diff line change
Expand Up @@ -869,14 +869,20 @@ public function canAccessConstants(): TrinaryLogic

public function hasConstant(string $constantName): TrinaryLogic
{
$class = $this->getClassReflection();
if ($class === null) {
$classReflection = $this->getClassReflection();
if ($classReflection === null) {
return TrinaryLogic::createMaybe();
}

if ($classReflection->hasConstant($constantName)) {
return TrinaryLogic::createYes();
}

if ($classReflection->isFinal()) {
return TrinaryLogic::createNo();
}

return TrinaryLogic::createFromBoolean(
$class->hasConstant($constantName),
);
return TrinaryLogic::createMaybe();
}

public function getConstant(string $constantName): ClassConstantReflection
Expand Down
35 changes: 35 additions & 0 deletions tests/PHPStan/Type/ObjectTypeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,41 @@ public function testAccepts(
);
}

public static function dataHasConstant(): Iterator
{
yield [
new ObjectType(DateTimeImmutable::class),
'ATOM',
TrinaryLogic::createYes(),
];
yield [
new ObjectType(DateTimeImmutable::class),
'CUSTOM',
TrinaryLogic::createMaybe(),
];
yield [
new ObjectType(Closure::class), // is final
'CUSTOM',
TrinaryLogic::createNo(),
];
yield [
new ObjectType('SomeNonExistingClass'),
'CUSTOM',
TrinaryLogic::createMaybe(),
];
}

#[DataProvider('dataHasConstant')]
public function testHasConstant(ObjectType $type, string $constantName, TrinaryLogic $expectedResult): void
{
$actualResult = $type->hasConstant($constantName);
$this->assertSame(
$expectedResult->describe(),
$actualResult->describe(),
sprintf('%s -> hasConstant("%s")', $type->describe(VerbosityLevel::precise()), $constantName),
);
}

public function testGetClassReflectionOfGenericClass(): void
{
$objectType = new ObjectType(Traversable::class);
Expand Down
Loading