[Node] add StmtsIterable interface to mark nodes that contain iterable stmts to improve hooking in node visitors #836
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
At the moment, there are nodes in php-parser, that include list of other stmts. While iterating over can be easy with
property_exists($node, 'stmts')
(feels like poor coding), the hooking to them via node visitors/Rector/PHPStan not so.At the moment hooking into them requries special constant and careful listing of all such nodes:
https://github.com/rectorphp/rector-src/blob/975fdf113fab99b6120383211e997da2c820bd0a/rules/CodeQuality/NodeTypeGroup.php
It happened we forgot some and then Rector rules were not applied.
These rules often work with previously used stmt, e.g. to remove already assigned value:
function setDefault() { - $value = 100; $value = 150; // ... }
This could be somehow achieved with next/previous/parent attributes. Yet PHPStan and Rector are moving away from next/previous/parent nodes for 2 reasons:
Assign
and otherExpr
can be deeply nested:Here removing
$value = 100
itself is ilegal and requires quite complex check to all parent nodes.Iterating only over all directly available stmts would make this no-brainer.
Where would be this interface be useful?
getNodeType()
) would be able to hook into those tooThis marker will dramatically simplify integration of new rules to work with stmts.
At first I thought we could have
class StmtsAware extends Stmt {}
, but sometimeExpr
contains$stmts
too:PHP-Parser/lib/PhpParser/Node/Expr/Closure.php
Lines 21 to 22 in 678ccbe
Thus interface marker choice. We're already using such marker interface in Rector via patching of php-parser nodes: https://github.com/rectorphp/rector/blob/d08b83c4264ba5b265890a049285518f79684644/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Foreach_.php#L8
And it works great 👍
What do you think?