Skip to content

Commit 1956c7f

Browse files
pepakrizondrejmirtes
authored andcommitted
Registry: support multiple rules registered by a single class
1 parent 941684d commit 1956c7f

File tree

3 files changed

+60
-2
lines changed

3 files changed

+60
-2
lines changed

src/Rules/Registry.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,11 @@ public function getRules(string $nodeType): array
3333
$rules = [];
3434
foreach ($nodeTypes as $nodeType) {
3535
foreach ($this->rules[$nodeType] ?? [] as $rule) {
36-
$rules[get_class($rule)] = $rule;
36+
$rules[] = $rule;
3737
}
3838
}
3939

40-
$this->cache[$nodeType] = array_values($rules);
40+
$this->cache[$nodeType] = $rules;
4141
}
4242

4343
return $this->cache[$nodeType];

tests/PHPStan/Rules/RegistryTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
namespace PHPStan\Rules;
44

5+
use PHPStan\Analyser\Scope;
6+
57
class RegistryTest extends \PHPStan\Testing\TestCase
68
{
79

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

25+
public function testGetRulesWithTwoDifferentInstances(): void
26+
{
27+
$fooRule = new UniversalRule(\PhpParser\Node\Expr\FuncCall::class, function (\PhpParser\Node\Expr\FuncCall $node, Scope $scope): array {
28+
return ['Foo error'];
29+
});
30+
$barRule = new UniversalRule(\PhpParser\Node\Expr\FuncCall::class, function (\PhpParser\Node\Expr\FuncCall $node, Scope $scope): array {
31+
return ['Bar error'];
32+
});
33+
34+
$registry = new Registry([
35+
$fooRule,
36+
$barRule,
37+
]);
38+
39+
$rules = $registry->getRules(\PhpParser\Node\Expr\FuncCall::class);
40+
$this->assertCount(2, $rules);
41+
$this->assertSame($fooRule, $rules[0]);
42+
$this->assertSame($barRule, $rules[1]);
43+
44+
$this->assertCount(0, $registry->getRules(\PhpParser\Node\Expr\MethodCall::class));
45+
}
46+
2347
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Rules;
4+
5+
use PhpParser\Node;
6+
use PHPStan\Analyser\Scope;
7+
8+
class UniversalRule implements Rule
9+
{
10+
11+
/** @var string */
12+
private $nodeType;
13+
14+
/** @var callable */
15+
private $processNodeCallback;
16+
17+
public function __construct(string $nodeType, callable $processNodeCallback)
18+
{
19+
$this->nodeType = $nodeType;
20+
$this->processNodeCallback = $processNodeCallback;
21+
}
22+
23+
public function getNodeType(): string
24+
{
25+
return $this->nodeType;
26+
}
27+
28+
public function processNode(Node $node, Scope $scope): array
29+
{
30+
$callback = $this->processNodeCallback;
31+
$callback($node, $scope);
32+
}
33+
34+
}

0 commit comments

Comments
 (0)