Skip to content

Commit

Permalink
Merge pull request #10634 from weirdan/10334-global-constants-as-case…
Browse files Browse the repository at this point in the history
…-values
  • Loading branch information
weirdan authored Feb 1, 2024
2 parents 38d7d43 + 421cb0f commit fc88ef2
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -283,23 +283,28 @@ public static function infer(
}

if ($stmt instanceof PhpParser\Node\Expr\ConstFetch) {
$name = strtolower($stmt->name->getFirst());
if ($name === 'false') {
$name = $stmt->name->getFirst();
$name_lowercase = strtolower($name);
if ($name_lowercase === 'false') {
return Type::getFalse();
}

if ($name === 'true') {
if ($name_lowercase === 'true') {
return Type::getTrue();
}

if ($name === 'null') {
if ($name_lowercase === 'null') {
return Type::getNull();
}

if ($stmt->name->getFirst() === '__NAMESPACE__') {
if ($name === '__NAMESPACE__') {
return Type::getString($aliases->namespace);
}

if ($type = ConstFetchAnalyzer::getGlobalConstType($codebase, $name, $name)) {
return $type;
}

return null;
}

Expand Down
66 changes: 66 additions & 0 deletions tests/EnumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,28 @@ function f(I $i): void {
'ignored_issues' => [],
'php_version' => '8.1',
],
'stringBackedEnumCaseValueFromStringGlobalConstant' => [
'code' => '<?php
enum Bar: string
{
case Foo = \DATE_ATOM;
}
',
'assertions' => [],
'ignored_issues' => [],
'php_version' => '8.1',
],
'intBackedEnumCaseValueFromIntGlobalConstant' => [
'code' => '<?php
enum Bar: int
{
case Foo = \UPLOAD_ERR_OK;
}
',
'assertions' => [],
'ignored_issues' => [],
'php_version' => '8.1',
],
];
}

Expand Down Expand Up @@ -1107,6 +1129,50 @@ enum Bar: int
'ignored_issues' => [],
'php_version' => '8.1',
],
'invalidStringBackedEnumCaseValueFromStringGlobalConstant' => [
'code' => '<?php
enum Bar: string
{
case Foo = \PHP_VERSION_ID;
}
',
'error_message' => 'InvalidEnumCaseValue',
'ignored_issues' => [],
'php_version' => '8.1',
],
'invalidIntBackedEnumCaseValueFromIntGlobalConstant' => [
'code' => '<?php
enum Bar: int
{
case Foo = \PHP_BINARY;
}
',
'error_message' => 'InvalidEnumCaseValue',
'ignored_issues' => [],
'php_version' => '8.1',
],
'invalidStringBackedEnumCaseValueFromIntGlobalConstant' => [
'code' => '<?php
enum Bar: string
{
case Foo = \PHP_BINARY;
}
',
'error_message' => 'InvalidEnumCaseValue',
'ignored_issues' => [],
'php_version' => '8.1',
],
'invalidIntBackedEnumCaseValueFromStringGlobalConstant' => [
'code' => '<?php
enum Bar: int
{
case Foo = \PHP_VERSION_ID;
}
',
'error_message' => 'InvalidEnumCaseValue',
'ignored_issues' => [],
'php_version' => '8.1',
],
];
}
}

0 comments on commit fc88ef2

Please sign in to comment.