Skip to content

Commit

Permalink
ForbidCustomFunctionsRule: better config validation (#83)
Browse files Browse the repository at this point in the history
  • Loading branch information
janedbal committed Feb 3, 2023
1 parent 411a5b3 commit c99e2b9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/Rule/ForbidCustomFunctionsRule.php
Expand Up @@ -20,6 +20,7 @@
use PHPStan\Type\TypeUtils;
use function count;
use function explode;
use function gettype;
use function is_string;
use function sprintf;

Expand All @@ -40,15 +41,19 @@ class ForbidCustomFunctionsRule implements Rule
private ReflectionProvider $reflectionProvider;

/**
* @param array<string, mixed> $forbiddenFunctions
* @param array<mixed, mixed> $forbiddenFunctions
*/
public function __construct(array $forbiddenFunctions, ReflectionProvider $reflectionProvider)
{
$this->reflectionProvider = $reflectionProvider;

foreach ($forbiddenFunctions as $forbiddenFunction => $description) {
if (!is_string($forbiddenFunction)) {
throw new LogicException("Unexpected forbidden function name, string expected, got $forbiddenFunction. Usage: ['var_dump' => 'Remove debug code!'].");
}

if (!is_string($description)) {
throw new LogicException('Unexpected forbidden function description, string expected');
throw new LogicException('Unexpected forbidden function description, string expected, got ' . gettype($description) . '. Usage: [\'var_dump\' => \'Remove debug code!\'].');
}

$parts = explode('::', $forbiddenFunction);
Expand Down
18 changes: 18 additions & 0 deletions tests/Rule/ForbidCustomFunctionsRuleTest.php
Expand Up @@ -35,4 +35,22 @@ public function testClass(): void
$this->analyseFile(__DIR__ . '/data/ForbidCustomFunctionsRule/code.php');
}

public function testInvalidConfig1(): void
{
self::expectExceptionMessage("Unexpected forbidden function name, string expected, got 0. Usage: ['var_dump' => 'Remove debug code!'].");
new ForbidCustomFunctionsRule(['var_dump'], $this->createMock(ReflectionProvider::class));
}

public function testInvalidConfig2(): void
{
self::expectExceptionMessage("Unexpected forbidden function description, string expected, got array. Usage: ['var_dump' => 'Remove debug code!'].");
new ForbidCustomFunctionsRule(['var_dump' => []], $this->createMock(ReflectionProvider::class));
}

public function testInvalidConfig3(): void
{
self::expectExceptionMessage('Unexpected format of forbidden function Class::method::12, expected Namespace\Class::methodName');
new ForbidCustomFunctionsRule(['Class::method::12' => 'Description'], $this->createMock(ReflectionProvider::class));
}

}

0 comments on commit c99e2b9

Please sign in to comment.