1212use PhpParser \Node \Expr \PropertyFetch ;
1313use PhpParser \Node \Expr \Ternary ;
1414use PhpParser \Node \Expr \Variable ;
15- use Rector \Provider \CurrentFileProvider ;
1615use Rector \Rector \AbstractRector ;
17- use Rector \ValueObject \Application \File ;
1816use Symplify \RuleDocGenerator \ValueObject \CodeSample \CodeSample ;
1917use Symplify \RuleDocGenerator \ValueObject \RuleDefinition ;
2018
@@ -25,13 +23,16 @@ final class DowngradeNullsafeToTernaryOperatorRector extends AbstractRector
2523{
2624 private int $ counter = 0 ;
2725
28- private ?string $ previousFileName = null ;
29-
30- private ?string $ currentFileName = null ;
31-
32- public function __construct (
33- private readonly CurrentFileProvider $ currentFileProvider
34- ) {
26+ /**
27+ * Hack-ish way to reset counter for a new file, to avoid rising counter for each file
28+ *
29+ * @param Node[] $nodes
30+ * @return array|Node[]|null
31+ */
32+ public function beforeTraverse (array $ nodes ): ?array
33+ {
34+ $ this ->counter = 0 ;
35+ return parent ::beforeTraverse ($ nodes );
3536 }
3637
3738 public function getRuleDefinition (): RuleDefinition
@@ -62,22 +63,6 @@ public function getNodeTypes(): array
6263 */
6364 public function refactor (Node $ node ): ?Ternary
6465 {
65- if ($ this ->previousFileName === null ) {
66- $ previousFile = $ this ->currentFileProvider ->getFile ();
67- if (! $ previousFile instanceof File) {
68- return null ;
69- }
70-
71- $ this ->previousFileName = $ previousFile ->getFilePath ();
72- }
73-
74- $ currentFile = $ this ->currentFileProvider ->getFile ();
75- if (! $ currentFile instanceof File) {
76- return null ;
77- }
78-
79- $ this ->currentFileName = $ currentFile ->getFilePath ();
80-
8166 $ nullsafeVariable = $ this ->createNullsafeVariable ();
8267
8368 $ methodCallOrPropertyFetch = $ node instanceof NullsafeMethodCall
@@ -91,13 +76,7 @@ public function refactor(Node $node): ?Ternary
9176
9277 private function createNullsafeVariable (): Variable
9378 {
94- if ($ this ->previousFileName !== $ this ->currentFileName ) {
95- $ this ->counter = 0 ;
96- $ this ->previousFileName = $ this ->currentFileName ;
97- }
98-
9979 $ nullsafeVariableName = 'nullsafeVariable ' . ++$ this ->counter ;
100-
10180 return new Variable ($ nullsafeVariableName );
10281 }
10382}
0 commit comments