Skip to content
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

Detect enum duplicated values #2371

Merged
merged 12 commits into from
May 23, 2023
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
97 changes: 97 additions & 0 deletions src/Rules/Classes/EnumSanityRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\ShouldNotHappenException;
use PHPStan\Type\VerbosityLevel;
use Serializable;
use function array_key_exists;
use function count;
use function implode;
use function sprintf;

/**
Expand Down Expand Up @@ -122,6 +125,100 @@ public function processNode(Node $node, Scope $scope): array
}
}

$enumCases = [];
foreach ($node->stmts as $stmt) {
if (!$stmt instanceof Node\Stmt\EnumCase) {
continue;
}
$caseName = $stmt->name->name;

if (($stmt->expr instanceof Node\Scalar\LNumber || $stmt->expr instanceof Node\Scalar\String_)) {
if ($node->scalarType === null) {
$errors[] = RuleErrorBuilder::message(sprintf(
'Enum %s is not backed, but case %s has value %s.',
$node->namespacedName->toString(),
$caseName,
$stmt->expr->value,
))
->identifier('enum.caseWithValue')
->line($stmt->getLine())
->nonIgnorable()
->build();
} else {
$caseValue = $stmt->expr->value;

if (!isset($enumCases[$caseValue])) {
$enumCases[$caseValue] = [];
}

$enumCases[$caseValue][] = $caseName;
}
}

if ($node->scalarType === null) {
continue;
}

if ($stmt->expr === null) {
$errors[] = RuleErrorBuilder::message(sprintf(
'Enum case %s::%s without type doesn\'t match the "%s" type.',
$node->namespacedName->toString(),
$caseName,
$node->scalarType->name,
))
->identifier('enum.missingCase')
->line($stmt->getLine())
->nonIgnorable()
->build();
continue;
}

if ($node->scalarType->name === 'int' && !($stmt->expr instanceof Node\Scalar\LNumber)) {
$errors[] = RuleErrorBuilder::message(sprintf(
'Enum case %s::%s type %s doesn\'t match the "int" type.',
$node->namespacedName->toString(),
$caseName,
$scope->getType($stmt->expr)->describe(VerbosityLevel::typeOnly()),
))
->identifier('enum.caseType')
->line($stmt->getLine())
->nonIgnorable()
->build();
}

$isStringBackedWithoutStringCase = $node->scalarType->name === 'string' && !($stmt->expr instanceof Node\Scalar\String_);
if (!$isStringBackedWithoutStringCase) {
continue;
}
$errors[] = RuleErrorBuilder::message(sprintf(
'Enum case %s::%s type %s doesn\'t match the "string" type.',
$node->namespacedName->toString(),
$caseName,
$scope->getType($stmt->expr)->describe(VerbosityLevel::typeOnly()),
))
->identifier('enum.caseType')
->line($stmt->getLine())
->nonIgnorable()
->build();
}
Copy link
Author

@kubk kubk May 6, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here I had to use early return (if (!$isStringBackedWithoutStringCase) {) because linter forced me to do that.

Early return is a great rule to reduce code complexity, but in my opinion in this situation it made the code a bit harder to follow. Because instead of this code:

foreach ($enumCases as $enumCase) {
  if ($isIntBackedWithoutIntValue) {
   // add error
  }
  if ($isStringBackedWithoutStringValue) {
   // add error
  }
}

we got:

foreach ($enumCases as $enumCase) {
  if ($isIntBackedWithoutIntValue) {
   // add error
  }
  if (!$isStringBackedWithoutStringValue) {
    continue;
  }
  // add error
}

I saw that this rule was even suppressed once in phpstan repository:

https://github.com/phpstan/phpstan-deprecation-rules/blob/9d366debb01a8097106174e46c9aa138d3bf1c01/src/Rules/Deprecations/FetchingDeprecatedConstRule.php#L30

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You might want to look into fine-tuning https://github.com/slevomat/coding-standard/blob/master/doc/control-structures.md#slevomatcodingstandardcontrolstructuresearlyexit-

I obviously can't speak for Ondřej, but the last time a similar thing like this was discussed it sounded like he is open to look into adapting it.


foreach ($enumCases as $caseValue => $caseNames) {
if (count($caseNames) <= 1) {
continue;
}

$errors[] = RuleErrorBuilder::message(sprintf(
'Enum %s has duplicate value %s for cases %s.',
$node->namespacedName->toString(),
$caseValue,
implode(', ', $caseNames),
))
->identifier('enum.duplicateValue')
->line($node->getLine())
->nonIgnorable()
->build();
}

return $errors;
}

Expand Down
26 changes: 25 additions & 1 deletion tests/PHPStan/Rules/Classes/EnumSanityRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,36 @@ public function testRule(): void
'Enum EnumSanity\EnumWithSerialize contains magic method __unserialize().',
81,
],
[
'Enum EnumSanity\EnumDuplicateValue has duplicate value 1 for cases A, E.',
86,
],
[
'Enum EnumSanity\EnumDuplicateValue has duplicate value 2 for cases B, C.',
86,
],
[
'Enum case EnumSanity\EnumInconsistentCaseType::FOO type string doesn\'t match the "int" type.',
105,
],
[
'Enum case EnumSanity\EnumInconsistentCaseType::BAR without type doesn\'t match the "int" type.',
106,
],
[
'Enum case EnumSanity\EnumInconsistentStringCaseType::BAR without type doesn\'t match the "string" type.',
110,
],
[
'Enum EnumSanity\EnumWithValueButNotBacked is not backed, but case FOO has value 1.',
114,
],
];

if (PHP_VERSION_ID >= 80100) {
$expected[] = [
'Enum EnumSanity\EnumMayNotSerializable cannot implement the Serializable interface.',
86,
117,
];
}

Expand Down
31 changes: 31 additions & 0 deletions tests/PHPStan/Rules/Classes/data/enum-sanity.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,37 @@ public function __unserialize(array $data) {
}
}

enum EnumDuplicateValue: int {
case A = 1;
case B = 2;
case C = 2;
case D = 3;
case E = 1;
}

enum ValidIntBackedEnum: int {
case A = 1;
case B = 2;
}

enum ValidStringBackedEnum: string {
case A = 'A';
case B = 'B';
}

enum EnumInconsistentCaseType: int {
case FOO = 'foo';
case BAR;
}

enum EnumInconsistentStringCaseType: string {
case BAR;
}

enum EnumWithValueButNotBacked {
case FOO = 1;
}

enum EnumMayNotSerializable implements \Serializable {

public function serialize() {
Expand Down