77use PhpParser \Node ;
88use PhpParser \Node \Arg ;
99use PhpParser \Node \Expr ;
10+ use PhpParser \Node \Expr \BooleanNot ;
1011use PhpParser \Node \Expr \FuncCall ;
1112use PhpParser \Node \Expr \New_ ;
1213use PhpParser \Node \Expr \Ternary ;
2728 */
2829final class DowngradeIteratorCountToArrayRector extends AbstractRector
2930{
31+ private const string SKIP_NODE = 'skip_node ' ;
32+
3033 public function __construct (
3134 private readonly ArgsAnalyzer $ argsAnalyzer ,
3235 ) {
@@ -65,10 +68,19 @@ function test(array|Traversable $data) {
6568 }
6669
6770 /**
68- * @param FuncCall $node
71+ * @param Ternary| FuncCall $node
6972 */
7073 public function refactor (Node $ node ): null |FuncCall
7174 {
75+ if ($ node instanceof Ternary) {
76+ $ this ->markIsArrayGuardedCall ($ node );
77+ return null ;
78+ }
79+
80+ if ($ node ->getAttribute (self ::SKIP_NODE ) === true ) {
81+ return null ;
82+ }
83+
7284 if (! $ this ->isNames ($ node , ['iterator_count ' , 'iterator_to_array ' ])) {
7385 return null ;
7486 }
@@ -107,6 +119,43 @@ public function refactor(Node $node): null|FuncCall
107119 return $ node ;
108120 }
109121
122+ /**
123+ * Skip the not-array branch of an is_array() check on the same expr, e.g.
124+ * is_array($data) ? $data : iterator_to_array($data)
125+ */
126+ private function markIsArrayGuardedCall (Ternary $ ternary ): void
127+ {
128+ $ cond = $ ternary ->cond ;
129+ $ notArrayBranch = $ ternary ->else ;
130+
131+ if ($ cond instanceof BooleanNot) {
132+ $ cond = $ cond ->expr ;
133+ $ notArrayBranch = $ ternary ->if ;
134+ }
135+
136+ if (! $ cond instanceof FuncCall || ! $ this ->isName ($ cond , 'is_array ' ) || $ cond ->isFirstClassCallable ()) {
137+ return ;
138+ }
139+
140+ if (! $ notArrayBranch instanceof FuncCall || $ notArrayBranch ->isFirstClassCallable ()) {
141+ return ;
142+ }
143+
144+ if (! $ this ->isNames ($ notArrayBranch , ['iterator_count ' , 'iterator_to_array ' ])) {
145+ return ;
146+ }
147+
148+ $ checkedArg = $ cond ->getArg ('value ' , 0 );
149+ $ iteratorArg = $ notArrayBranch ->getArg ('iterator ' , 0 );
150+ if (! $ checkedArg instanceof Arg || ! $ iteratorArg instanceof Arg) {
151+ return ;
152+ }
153+
154+ if ($ this ->nodeComparator ->areNodesEqual ($ checkedArg ->value , $ iteratorArg ->value )) {
155+ $ notArrayBranch ->setAttribute (self ::SKIP_NODE , true );
156+ }
157+ }
158+
110159 private function isArrayIteratorWrapped (Expr $ expr ): bool
111160 {
112161 if (! $ expr instanceof Ternary) {
@@ -130,6 +179,12 @@ private function shouldSkip(Type $type): bool
130179 return false ;
131180 }
132181
182+ // never an array, e.g. narrowed by is_array($data) ? $data : iterator_to_array($data),
183+ // so the is_array() check would always be false
184+ if ($ type ->isArray ()->no ()) {
185+ return true ;
186+ }
187+
133188 $ type = TypeCombinator ::removeNull ($ type );
134189 return $ type ->isObject ()
135190 ->yes ();
0 commit comments