Skip to content

Commit

Permalink
Fix constant-string handling in union-types
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm committed Dec 21, 2022
1 parent 4a72d15 commit dc0cced
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/Type/UnionType.php
Expand Up @@ -17,6 +17,7 @@
use PHPStan\ShouldNotHappenException;
use PHPStan\TrinaryLogic;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\Generic\GenericClassStringType;
use PHPStan\Type\Generic\TemplateMixedType;
use PHPStan\Type\Generic\TemplateType;
Expand Down Expand Up @@ -77,6 +78,24 @@ public function getTypes(): array
return $this->types;
}

/**
* @param class-string<Type> $typeClass
* @return list<Type>
*/
private function getTypesOfClass(string $typeClass): array
{
$matchingTypes = [];
foreach ($this->getTypes() as $innerType) {
if (!$innerType instanceof $typeClass) {
return [];
}

$matchingTypes[] = $innerType;
}

return $matchingTypes;
}

public function isNormalized(): bool
{
return $this->normalized;
Expand Down Expand Up @@ -117,7 +136,7 @@ public function getConstantArrays(): array

public function getConstantStrings(): array
{
return UnionTypeHelper::getConstantStrings($this->getTypes());
return UnionTypeHelper::getConstantStrings($this->getTypesOfClass(ConstantStringType::class));
}

public function accepts(Type $type, bool $strictTypes): TrinaryLogic
Expand Down
1 change: 1 addition & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Expand Up @@ -1154,6 +1154,7 @@ public function dataFileAsserts(): iterable
yield from $this->gatherAssertTypes(__DIR__ . '/data/pathinfo-php8.php');
}
yield from $this->gatherAssertTypes(__DIR__ . '/data/pathinfo.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-8568.php');
}

/**
Expand Down
18 changes: 18 additions & 0 deletions tests/PHPStan/Analyser/data/bug-8568.php
@@ -0,0 +1,18 @@
<?php declare(strict_types = 1);

namespace Bug8568;

use function PHPStan\Testing\assertType;

class HelloWorld
{
public function sayHello(): void
{
assertType('non-falsy-string', 'a' . $this->get());
}

public function get(): ?int
{
return rand() ? 5 : null;
}
}

0 comments on commit dc0cced

Please sign in to comment.