Skip to content

ClassPropertyAssignToConstructorPromotionRector doesn't check dependencies in setter hooks. Resulting in a UninitializedPropertyError #9640

@rensPols

Description

@rensPols

Bug Report

Subject Details
Rector version 2.3.6
PHP version 8.4

Minimal PHP Code Causing Issue

getrector.com

<?php

final class DemoFile
{
    public mixed $value {
    	get {
        	return $this->value;
        }
        set {
            if ($this->optionUsedInValueSetter) {
            	$this->value = "changed value";
            }
            $this->value = $value;
        }
    }
    
    public function __construct(
    	mixed $value,
        bool $optionUsedInValueSetter = false,
    ) {
    	$this->value = $value;
    }
}

Is changed to (With the Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector rule):

<?php
 
  final class DemoFile
  {
    public function __construct(public mixed $value {
      get {
        return $this->value;
      }
      set {
        if ($this->optionUsedInValueSetter) {
          $this->value = "changed value";
        }
        $this->value = $value;
  }
  }, bool $optionUsedInValueSetter = false)
  {
  }
}

But this causes $this->optionUsedInValueSetter to be called before it's initialised.

Expected Behaviour

When a variable has a setter that is dependent on a value that is later initialised in the constructor than itself, it shouldn't move the getters and setters to the constructor.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions