php-formatter icon indicating copy to clipboard operation
php-formatter copied to clipboard

Use sorting tries fixing traits in rare case

Open matt-usurp opened this issue 8 years ago • 0 comments

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.

matt-usurp avatar Nov 13 '17 11:11 matt-usurp