Skip to content

Commit

Permalink
forbidEnumInFunctionArguments: allow array_unique($enums, SORT_REGULA…
Browse files Browse the repository at this point in the history
…R) (#196)
  • Loading branch information
janedbal committed Dec 22, 2023
1 parent baa841c commit 0512340
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/Rule/ForbidEnumInFunctionArgumentsRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use function array_key_exists;
use function count;
use function implode;
use const SORT_REGULAR;

/**
* @template-implements Rule<FuncCall>
Expand All @@ -30,6 +31,9 @@ class ForbidEnumInFunctionArgumentsRule implements Rule
private const REASON_UNPREDICTABLE_RESULT = 'as the function causes unexpected results'; // https://3v4l.org/YtGVa
private const REASON_SKIPS_ENUMS = 'as the function will skip any enums and produce warning';

/**
* Function name -> [forbidden argument position, reason]]
*/
private const FUNCTION_MAP = [
'array_intersect' => [self::ANY_ARGUMENT, self::REASON_IMPLICIT_TO_STRING],
'array_intersect_assoc' => [self::ANY_ARGUMENT, self::REASON_IMPLICIT_TO_STRING],
Expand Down Expand Up @@ -90,12 +94,16 @@ public function processNode(Node $node, Scope $scope): array
}

foreach ($funcCall->getArgs() as $position => $argument) {
$argumentType = $scope->getType($argument->value);

if ($functionName === 'array_unique' && $position === 1 && $argumentType->getConstantScalarValues() === [SORT_REGULAR]) {
return []; // this edgecase seems to be working fine
}

if (!$this->matchesPosition((int) $position, $forbiddenArgumentPosition)) {
continue;
}

$argumentType = $scope->getType($argument->value);

if ($this->containsEnum($argumentType)) {
$wrongArguments[] = (int) $position + 1;
}
Expand Down
5 changes: 5 additions & 0 deletions tests/Rule/data/ForbidEnumInFunctionArgumentsRule/code.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,9 @@ public function testArgumentsNormalization()
sort(flags: 0, array: [SomeEnum::Bar]); // error: Argument 1 in sort() cannot contain enum as the function causes unexpected results
}

public function testArrayUniqueWithSortRegular() {
$enums = [SomeEnum::Bar, SomeEnum::Baz, SomeEnum::Bar];
array_unique($enums, SORT_REGULAR); // https://3v4l.org/XF7Ua
}

}

0 comments on commit 0512340

Please sign in to comment.