Skip to content

Incorrect behavior of ReadOnlyPropertyRector #8106

@petski

Description

@petski

Bug Report

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

Minimal PHP Code Causing Issue

See https://getrector.com/demo/17e5b3b3-d8ac-4f67-b40c-e2b0ef2d04dd

<?php

namespace Rector\Tests\Php81\Rector\Property\ReadOnlyPropertyRector\Fixture;

class SkipAssignPlusCallByRefGlobal {
    private array $fruits;
    
    public function __construct() {
        $this->fruits = ['banana', 'pear', 'apple'];
        \sort($this->fruits);
    }
}
@@ -3,7 +3,7 @@
 namespace Rector\Tests\Php81\Rector\Property\ReadOnlyPropertyRector\Fixture;
 
 class SkipAssignPlusCallByRefGlobal {
-    private array $fruits;
+    private readonly array $fruits;
     
     public function __construct() {
         $this->fruits = ['banana', 'pear', 'apple'];

Responsible rules

  • ReadOnlyPropertyRector

Expected Behavior

Making private array $fruits readonly is incorrect, as it could (in this case will) be modified by the sort() call, after it is initiated. Rector shouldn't patch this.

With the above rector patch applied, php will throw an error, see https://3v4l.org/5POee

FWIW: phpstan will complain with a Parameter #1 $array is passed by reference so it does not accept readonly property

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