phpvisual-studio-codeautomated-refactoring

Update namespace and imports of other files after moving class


Does anyone know if it's possible to configure VSCode to have the following occur after moving a file to another locations?

For example, let's say I have the following classes in src/app:

src/app/Hello.php

<?php

namespace App;

class Hello {
...
}

src/app/Goodbye.php

<?php

namespace App;

use App\Hello;

class Goodbye {
...
}

I want to move my src/app/Hello.php file into src/app/services/Hello.php. The following should occur:

So then we will have: src/app/services/Hello.php

<?php

namespace App\Services;

class Hello {
...
}

src/app/Goodbye.php

<?php

namespace App;

use App\Services\Hello;

class Goodbye {
...
}

Can this be done with the PHP Intelephense or PHP Namespace Resolver extension, or by any other means?


Solution

  • This can be done with the paid version of Intelepense. In VSCode, you have to do "rename symbol" (via right click context menu or press F2) on the namespace declaration in the file and it will automatically move the file to the correct folder and change all occurrences.

    For example if you have a file Foo/Baz.php:

    <?php
    
    namespace Foo;
    
    class Baz {}
    

    Perform "rename symbol" on Foo and change it to Foo\Bar.

    Now that file will be moved to Foo/Bar/Baz.php and the namespace declaration will change:

    <?php
    
    namespace Foo\Bar;
    
    class Baz {}
    

    And so will all the occurrences of Baz in other files:

    <?php
    
    use Foo\Bar\Baz; # Instead of use Foo\Baz.
    
    use Foo\Bar\Baz as Bap; # Instead of use Foo\Baz as Bap.
    
    new Foo\Bar\Baz; # Instead of new Foo\Baz.
    
    # And so on...