Update namespace and imports of other files after moving class
Asked Answered
P

1

9

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

  • Update the namespace of the class/trait.
  • Update the imports of all other files referencing this file.

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:

  • The namespace changes from namespace App to namespace App\Services
  • The import in src/app/Goodbye.php changes from use App\Hello to use App\Services\Hello

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?

Postmistress answered 21/6, 2021 at 20:35 Comment(0)
G
0

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...
Granuloma answered 1/7 at 17:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.