kokororin / vscode-phpfmt

Integrates phpfmt into VS Code
https://marketplace.visualstudio.com/items?itemName=kokororin.vscode-phpfmt
BSD 3-Clause "New" or "Revised" License
129 stars 30 forks source link

PHP8: attributes with "\", needed "use" removed on formatting #117

Closed ili101 closed 10 months ago

ili101 commented 10 months ago

Before:

<?php

namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    #[Assert\NotBlank]
    public string $name;
}

After:

<?php

namespace App\Entity;

class Author
{
    #[Assert\NotBlank]
    public string $name;
}

Example from: https://symfony.com/doc/current/validation.html#the-basics-of-validation

driade commented 10 months ago

Hi, good morning.

I think I can achieve this case

#[Assert\NotBlank]

but, due to the nature of Attributes in PHP it'd be far far from perfect. Things like

 #[Attribute(Attribute::TARGET_CLASS_CONSTANT|Attribute::TARGET_PROPERTY)]

won't be really doable as the contents of the Attributes, when parsed, are treated like "strings". So, the parser wouldn't know if "Attribute::TARGET_PROPERTY " is a class constante (though it obviously seems to) or just a string you use to mark your code. The same happens with

#[Test]

Is it a class? A "tag"? We would've to do a lot of magic to try to guess what is a class and what's not inside an attribute.

While I think about it I'd recommend disabling "OrderAndRemoveUseClauses" and enabling "OnlyOrderUseClauses".

Any though about this would be appreciated :)

ili101 commented 10 months ago

Hi thank you I added the workaround to .vscode/settings.json for now

    "phpfmt.exclude": [
        "OrderAndRemoveUseClauses"
    ],
    "phpfmt.passes": [
        "OnlyOrderUseClauses"
    ],

I didn't understand why you say that the same happens with #[Test], for example this has no problem, the "use" isn't removed

<?php

namespace App\Entity;

use Symfony\Component\Validator\Constraints\Ip as AssertIp;

class Author
{
    #[AssertIp]
    public string $name;
}

I now see it's probably not related to attributes but actually any "use" of something that you then use only its child, this "use" also getting removed:

<?php

namespace App\Entity;

use Symfony\Component\Validator\Constraints;

new Constraints\Ip();
driade commented 10 months ago

Hi @ili101 I've uploaded a patch, not a perfect one but it'd be good. May you please check?

I'll the other case you mention.

ili101 commented 10 months ago

As far as I see both examples are working correctly now (: