[php 8.4] Add array_find function upgrade rule
$animals = ['dog', 'cat', 'cow', 'duck', 'goose'];
-$found = null;
-foreach ($animals as $animal) {
- if (str_starts_with($animal, 'c')) {
- $found = $animal;
- break;
- }
-}
+$found = array_find($animals, fn($animal) => str_starts_with($animal, 'c'));
There are other functions that exist in php 8.4:
- array_any
- array_all
array_find - https://github.com/rectorphp/rector-src/pull/7009
array_find_key - https://github.com/rectorphp/rector-src/pull/7008
array_any - https://github.com/rectorphp/rector-src/pull/7010
array_all - https://github.com/rectorphp/rector-src/pull/7011
Let me know if you need changes with either.
Downgrade rule(s) is needed for this so new transformed to php 8.4 array_ code can be downgraded
https://github.com/rectorphp/rector-downgrade-php
Downgrade rule(s) is needed for this so new transformed to php 8.4
array_code can be downgraded
I didn't even know this existed - I might file a PR with the changes. 👀
Awesome, after rule created, register to downgrade config set https://github.com/rectorphp/rector-downgrade-php/blob/main/config/set/downgrade-php84.php
ForeachToArrayFindKeyRector replaces code using iterable objects (instead of arrays).
$animals = new \ArrayIterator(['dog', 'cat', 'cow', 'duck', 'goose']);
$found = null;
foreach ($animals as $idx => $animal) {
if (str_starts_with($animal, 'c')) {
$found = $idx;
break;
}
}
is replaced by:
$animals = new \ArrayIterator(['dog', 'cat', 'cow', 'duck', 'goose']);
$found = array_find_key($animals, fn($animal) => str_starts_with($animal, 'c'));
which is invalid, because array_find_key only supports arrays.
Did not check the other rules.
(Note that it is not reproducible on getrector.com. But the example from ForeachToArrayFindKeyRector.com is also not working there).
@gharlan php version 80400 need to be set on demo page to be able to reproduce https://getrector.com/demo/89a7b249-f374-4868-b328-30a883b833be
@gharlan I created PR:
- https://github.com/rectorphp/rector-src/pull/7023
for that to skip non-array.
Nice catch @gharlan, I completely forgot about the existence of iterables. Oh well. Thanks @samsonasik for the quick fix!
Thanks everyone for quick work 💪
@TomasVotruba the downgrade rules still needed, I think this can be re-open to avoid user upgrade to php 8.4, and can't downgrade to php < 8.4
This issue has been automatically locked because it has been closed for 150 days. Please open a new issue if you have a similar problem.