Skip to content

Fix string types sorting #3441

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 15, 2024
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
4 changes: 4 additions & 0 deletions src/Type/UnionTypeHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ public static function sortTypes(array $types): array
return self::compareStrings($a->describe(VerbosityLevel::value()), $b->describe(VerbosityLevel::value()));
}

if ($a->isString()->yes() && $b->isString()->yes()) {
return self::compareStrings($a->describe(VerbosityLevel::value()), $b->describe(VerbosityLevel::value()));
}

return self::compareStrings($a->describe(VerbosityLevel::typeOnly()), $b->describe(VerbosityLevel::typeOnly()));
});
return $types;
Expand Down
20 changes: 20 additions & 0 deletions tests/PHPStan/Analyser/nsrt/string-union.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php declare(strict_types = 1);

namespace StringUnion;

use function PHPStan\Testing\assertType;

class HelloWorld
{
/**
* @param literal-string $s1
* @param numeric-string $s2
*/
public function sayHello(string $s1, string $s2): void
{
$a = random_int(0, 1) ? $s1 : $s2;
assertType('literal-string|numeric-string', $a);
$b = random_int(0, 1) ? $s2 : $s1;
assertType('literal-string|numeric-string', $b);
}
}
8 changes: 8 additions & 0 deletions tests/PHPStan/Type/TypeCombinatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1960,6 +1960,14 @@ public function dataUnion(): iterable
UnionType::class,
'string|false',
],
[
[
new IntersectionType([new StringType(), new AccessoryNumericStringType()]),
new IntersectionType([new StringType(), new AccessoryLiteralStringType()]),
],
UnionType::class,
'literal-string|numeric-string',
],
[
[
TemplateTypeFactory::create(
Expand Down
Loading