DEVSENSE / phptools-docs

PHP Tools public content
Apache License 2.0
81 stars 10 forks source link

Improvement of quick fix `Add construct from properties ...` #198

Open Zerotask opened 1 year ago

Zerotask commented 1 year ago

Assume you have the following:

<?php

class User
{
    private ?string $name;
    private int $age;
    private bool $isDeveloper;
}

The quick fix will generate the following:

<?php

class User
{
    private ?string $name;
    private int $age;
    private bool $isDeveloper;
    /**
     * @param $name ?string
     * @param $age int
     * @param $isDeveloper bool
     */
    function __construct(?string $name, int $age, bool $isDeveloper) {
        $this->name = $name;
        $this->age = $age;
        $this->isDeveloper = $isDeveloper;
    }
}

Suggestions:

  1. insert a new line before
  2. docblocks: swap param name and data type: @param $age int -> @param int $age
  3. docblocks: null is not ?: @param $name ?string -> @param null|string $name
  4. Add visibility (public by default)
  5. apply configured code formatting (in my case PSR12) -> have to click ctrl + s and then it gets formatted for PSR12

The expected output would be:

<?php

class User
{
    private ?string $name;
    private int $age;
    private bool $isDeveloper;

    /**
     * @param null|string $name
     * @param int $age
     * @param bool $isDeveloper
     */
    public function __construct(?string $name, int $age, bool $isDeveloper)
    {
        $this->name = $name;
        $this->age = $age;
        $this->isDeveloper = $isDeveloper;
    }
}
Zerotask commented 1 year ago

A great addition would be to add properties to an already present constructor. This would also be helpful for #192 Example:

<?php

class User
{
    private ?string $name;
    private int $age;
    private bool $isDeveloper;
    private string $lastName;

    /**
     * @param null|string $name
     * @param int $age
     * @param bool $isDeveloper
     */
    public function __construct(?string $name, int $age, bool $isDeveloper)
    {
        $this->name = $name;
        $this->age = $age;
        $this->isDeveloper = $isDeveloper;
    }
}

Now I'd like to have it as follows:

<?php

class User
{
    private ?string $name;
    private int $age;
    private bool $isDeveloper;
    private string $lastName;

    /**
     * @param null|string $name
     * @param int $age
     * @param bool $isDeveloper
     * @param string $lastName
     */
    public function __construct(?string $name, int $age, bool $isDeveloper, string $lastName)
    {
        $this->name = $name;
        $this->age = $age;
        $this->isDeveloper = $isDeveloper;
        $this->lastName = $lastName;
    }
}

(docblock, param and assignment)

There could be a quick fix for properties to be added to the constructor and/or a quick fix for the class to sync properties with the constructor

jakubmisek commented 1 year ago

thank you for the detailed suggestions! Working on it: