Skip to content

Incorrect behavior of RemoveDeadLoopRector #9048

Closed
rectorphp/rector-src
#6770
@AndrolGenhald

Description

@AndrolGenhald

Bug Report

Subject Details
Rector version last dev-main
Installed as composer dependency

Minimal PHP Code Causing Issue

See https://getrector.com/demo/a2430be9-e87c-461a-8a5b-9c54c9fca4e2 and https://getrector.com/demo/63ac88aa-c163-4719-8d78-a0c2ce01b7d6

<?php

$arr = [
    new DateTimeImmutable("2025-03-10 00:00:00"),
    new DateTimeImmutable("2025-03-14 00:00:00"),
    new DateTimeImmutable("2025-03-18 00:00:00"),
    new DateTimeImmutable("2025-03-22 00:00:00"),
    new DateTimeImmutable("2025-03-26 00:00:00"),
    new DateTimeImmutable("2025-03-30 00:00:00"),
];
$checkDate = new DateTimeImmutable("2025-03-20 00:00:00");
for($foundDate = array_shift($arr); $foundDate !== null && $foundDate < $checkDate; $foundDate = array_shift($arr));

var_dump($foundDate);
<?php

$arr = [
    new DateTimeImmutable("2025-03-10 00:00:00"),
    new DateTimeImmutable("2025-03-14 00:00:00"),
    new DateTimeImmutable("2025-03-18 00:00:00"),
    new DateTimeImmutable("2025-03-22 00:00:00"),
    new DateTimeImmutable("2025-03-26 00:00:00"),
    new DateTimeImmutable("2025-03-30 00:00:00"),
];
$checkDate = new DateTimeImmutable("2025-03-20 00:00:00");
$foundDate = array_shift($arr);
while ($foundDate < $checkDate && ($foundDate = array_shift($arr)) !== null);

var_dump($foundDate);

Responsible rules

  • RemoveDeadLoopRector

Expected Behavior

The loops should not be removed since their side-effects are important. Not sure how feasible it is, but if possible it would be great to check if the variable being assigned in the loop is used later, and then consider the loop "not dead". If that's not feasible, I think it might be good to ignore loops that end with a semicolon, which generally indicates that the loop is supposed to be empty and exists for its side-effects.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions