Skip to content

Fix phpstan/phpstan#14252: Enum case outside of enum should be reported#5188

Open
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-43pdpis
Open

Fix phpstan/phpstan#14252: Enum case outside of enum should be reported#5188
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-43pdpis

Conversation

@phpstan-bot
Copy link
Collaborator

Summary

PHPStan did not report an error when an enum case declaration appeared inside a regular class or interface (instead of an enum). PHP itself produces a fatal error "Case can only be used in enums" for such code, but PHPStan silently accepted it.

Changes

  • Added src/Rules/EnumCases/EnumCaseOutsideEnumRule.php — a new rule that checks if Node\Stmt\EnumCase appears inside a non-enum class and reports "Enum case can only be used in enums."
  • Added tests/PHPStan/Rules/EnumCases/EnumCaseOutsideEnumRuleTest.php — test case for the new rule
  • Added tests/PHPStan/Rules/EnumCases/data/bug-14252.php — test data with enum case in class, interface, and enum (enum case in enum should not error)

Root cause

There was no rule checking whether EnumCase AST nodes appear in the correct context. The parser (nikic/php-parser) parses case Active; as Node\Stmt\EnumCase regardless of whether it's inside an enum or a class/interface. PHPStan had rules for validating enum case attributes and sanity checks within enums, but nothing to catch an enum case declaration outside of an enum.

Test

The regression test verifies that:

  • case Active; inside a class reports an error on line 9
  • case Active; inside an interface reports an error on line 14
  • case Active; inside an enum does NOT report an error (line 19)

Fixes phpstan/phpstan#14252

- Added new EnumCaseOutsideEnumRule that reports an error when `case` is used in classes or interfaces instead of enums
- New regression test in tests/PHPStan/Rules/EnumCases/data/bug-14252.php
- The rule is registered at level 0 and uses the identifier `enum.caseOutsideOfEnum`

Closes phpstan/phpstan#14252
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant