kubawerlos/php-cs-fixer-custom-fixers

PromotedConstructorPropertyFixer should check variable names

Closed this issue · 1 comments

I've encountered a strange problem with PromotedConstructorPropertyFixer. I have a class extending another class with a field named $data. Child class has overwritten constructor:

    protected array $fullData = [];

    public function __construct(array $data)
    {
        if (isset($data[Main::FIELDS])) {
            $this->data = $data[Main::FIELDS];
            $this->fullData = $data;
        } else {
            $this->throwException(Main::FIELDS);
        }
    }

Probably it should be written as this:

    protected array $fullData = [];

    public function __construct(array $data)
    {
        if (isset($data[Main::FIELDS])) {
            parent::__construct($data[Main::FIELDS])
            $this->fullData = $data;
        } else {
            $this->throwException(Main::FIELDS);
        }
    }

PHP-CS-Fixer is wrongly renaming my parameter, because probably it thinks it should be transformed into promoted constructor parameter:

 class RequestExtractor extends BaseExtractor
 {
-    protected array $fullData = [];
-
     /**
      * @throws BaseExtractorException
      * @throws JsonException
      */
-    public function __construct(array $data)
-    {
+    public function __construct(
+        protected array $fullData,
+    ) {
         if (isset($data[Main::FIELDS])) {
             $this->data = $data[Main::FIELDS];
-            $this->fullData = $data;
         } else {
             $this->throwException(Main::FIELDS);
         }

I omitted problem with little hack, but this is not how it should be done:

    public function __construct(array $data)
    {
        if (isset($data[Main::FIELDS])) {
            parent::__construct($data[Main::FIELDS]);
            $this->fullData = $data ?? [];
        } else {
            $this->throwException(Main::FIELDS);
        }
    }

I think that maybe - just maybe! - checking if the field in question and constructor parameter name are the same would solve problems like this.

I think that maybe - just maybe! - checking if the field in question and constructor parameter name are the same would solve problems like this.

It was renamed earlier, not when promoting all entries of local variable are renamed.