Skip to content

Commit

Permalink
Registry: support multiple rules registered by a single class
Browse files Browse the repository at this point in the history
  • Loading branch information
pepakriz authored and ondrejmirtes committed Jun 18, 2018
1 parent 941684d commit 1956c7f
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Rules/Registry.php
Expand Up @@ -33,11 +33,11 @@ public function getRules(string $nodeType): array
$rules = [];
foreach ($nodeTypes as $nodeType) {
foreach ($this->rules[$nodeType] ?? [] as $rule) {
$rules[get_class($rule)] = $rule;
$rules[] = $rule;
}
}

$this->cache[$nodeType] = array_values($rules);
$this->cache[$nodeType] = $rules;
}

return $this->cache[$nodeType];
Expand Down
24 changes: 24 additions & 0 deletions tests/PHPStan/Rules/RegistryTest.php
Expand Up @@ -2,6 +2,8 @@

namespace PHPStan\Rules;

use PHPStan\Analyser\Scope;

class RegistryTest extends \PHPStan\Testing\TestCase
{

Expand All @@ -20,4 +22,26 @@ public function testGetRules(): void
$this->assertCount(0, $registry->getRules(\PhpParser\Node\Expr\MethodCall::class));
}

public function testGetRulesWithTwoDifferentInstances(): void
{
$fooRule = new UniversalRule(\PhpParser\Node\Expr\FuncCall::class, function (\PhpParser\Node\Expr\FuncCall $node, Scope $scope): array {
return ['Foo error'];
});
$barRule = new UniversalRule(\PhpParser\Node\Expr\FuncCall::class, function (\PhpParser\Node\Expr\FuncCall $node, Scope $scope): array {
return ['Bar error'];
});

$registry = new Registry([
$fooRule,
$barRule,
]);

$rules = $registry->getRules(\PhpParser\Node\Expr\FuncCall::class);
$this->assertCount(2, $rules);
$this->assertSame($fooRule, $rules[0]);
$this->assertSame($barRule, $rules[1]);

$this->assertCount(0, $registry->getRules(\PhpParser\Node\Expr\MethodCall::class));
}

}
34 changes: 34 additions & 0 deletions tests/PHPStan/Rules/UniversalRule.php
@@ -0,0 +1,34 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules;

use PhpParser\Node;
use PHPStan\Analyser\Scope;

class UniversalRule implements Rule
{

/** @var string */
private $nodeType;

/** @var callable */
private $processNodeCallback;

public function __construct(string $nodeType, callable $processNodeCallback)
{
$this->nodeType = $nodeType;
$this->processNodeCallback = $processNodeCallback;
}

public function getNodeType(): string
{
return $this->nodeType;
}

public function processNode(Node $node, Scope $scope): array
{
$callback = $this->processNodeCallback;
$callback($node, $scope);
}

}

0 comments on commit 1956c7f

Please sign in to comment.