Skip to content

Incorrect behavior of TypedPropertyFromStrictConstructorRector #7840

@aboyton

Description

@aboyton

Bug Report

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

Minimal PHP Code Causing Issue

See https://getrector.com/demo/613f6ed1-6961-4926-9878-82c0c48a8e41

class Project {
    private $name;

    public function __construct(mixed $name) {
        if ($name === null) {
            $name = 'default';
        }
        $this->name = $name;
    }
}

$project = new Project(['name' => 123]);

Responsible rules

  • TypedPropertyFromStrictConstructorRector

Expected Behavior

Rector is incorrectly assuming it's safe to convert the type of the property $name to string, even though the constructor can take in any value. Setting the parameter type for the constructor to mixed` or leaving it unspecified has the same incorrect behaviour.

This but doesn't occur if you

  • change the if to if ($name === null) { $this->name = 'default'; } else { $this->name = $name; }
  • change the if to a ternary $this->name = $name === null ? 'default' : $name;
  • change the constructor to take a $name of type int (then it correctly changes the property $name to be int | string).

This obviously is concerning as this appears to do exactly what is specified wouldn't happen in https://getrector.com/blog/new-in-rector-015-complete-safe-and-known-type-declarations, namely that it won't add types it can't know are correct.

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