Skip to content

Commit e72ef39

Browse files
committed
Introduced NodeConnectingVisitor to be able to look around the current node in rules
1 parent e964816 commit e72ef39

File tree

4 files changed

+79
-0
lines changed

4 files changed

+79
-0
lines changed

conf/config.neon

+4
Original file line numberDiff line numberDiff line change
@@ -274,10 +274,14 @@ services:
274274
class: PhpParser\NodeTraverser
275275
setup:
276276
- addVisitor(@PhpParser\NodeVisitor\NameResolver)
277+
- addVisitor(@PhpParser\NodeVisitor\NodeConnectingVisitor)
277278

278279
-
279280
class: PhpParser\NodeVisitor\NameResolver
280281

282+
-
283+
class: PhpParser\NodeVisitor\NodeConnectingVisitor
284+
281285
-
282286
class: PhpParser\Parser\Php7
283287

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Rules;
4+
5+
use PhpParser\Node;
6+
use PHPStan\Analyser\Scope;
7+
8+
/**
9+
* @implements Rule<Node\Stmt\Echo_>
10+
*/
11+
class NodeConnectingRule implements Rule
12+
{
13+
14+
public function getNodeType(): string
15+
{
16+
return Node\Stmt\Echo_::class;
17+
}
18+
19+
public function processNode(Node $node, Scope $scope): array
20+
{
21+
return [
22+
sprintf(
23+
'Parent: %s, previous: %s, next: %s',
24+
get_class($node->getAttribute('parent')),
25+
get_class($node->getAttribute('previous')),
26+
get_class($node->getAttribute('next')),
27+
),
28+
];
29+
}
30+
31+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Rules;
4+
5+
use PHPStan\Testing\RuleTestCase;
6+
7+
/**
8+
* @extends RuleTestCase<NodeConnectingRule>
9+
*/
10+
class NodeConnectingRuleTest extends RuleTestCase
11+
{
12+
13+
protected function getRule(): Rule
14+
{
15+
return new NodeConnectingRule();
16+
}
17+
18+
public function testRule(): void
19+
{
20+
$this->analyse([__DIR__ . '/data/node-connecting.php'], [
21+
[
22+
'Parent: PhpParser\Node\Stmt\If_, previous: PhpParser\Node\Stmt\Switch_, next: PhpParser\Node\Stmt\Foreach_',
23+
11,
24+
],
25+
]);
26+
}
27+
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
namespace NodeConnecting;
4+
5+
function foobar(): void
6+
{
7+
if (rand(0, 1)) {
8+
switch ('foo') {
9+
default: 'bar';
10+
}
11+
echo 'test';
12+
foreach ([] as $val) {
13+
14+
}
15+
}
16+
}

0 commit comments

Comments
 (0)