mmoreram / php-formatter

PHP Formatter is a PHP developer friendly set of tools
MIT License
166 stars 17 forks source link

Use sorting tries fixing traits in rare case #33

Open matt-usurp opened 6 years ago

matt-usurp commented 6 years ago

The use:sort command appears to have a bug where a class that has no imports but uses a trait from the same namespace it will treat the trait usage as if it was a file level import. This is causing issues in our builds which will fail the code on bad smell.

The replication is pretty simple. Have one class and a trait in the same namespace, make the class use the trait without import (as you should). In the examples below I added a method also to demonstrate that it also messes with the formatting of methods.

The command:

vendor/bin/php-formatter formatter:use:sort src --ansi

File structure:

src/MyTrait.php
src/MyClass.php

The class:

<?php

namespace SomeNamespace;

class MyClass
{
    use MyTrait;

    public function something() 
    {
        return 1;
    }
}

Now run the command above on the src directory and the output will look something like this:

<?php

namespace SomeNamespace;

class MyClass
{

use MyTrait;

public function something() 
    {
        return 1;
    }
}

Now obviously the temporary fix for this is to import the trait. Unless you are using an auto code formatter in which it will remove the useless import and then you are back where you started. Have you come across this issue? Personally I have never written a trait in the same directory as something implementing it one of my co-workers has and now this problem falls on me.