Eclipse - Using file name conventions to refactor php classes

I am new to eclipse and am using version Version: Mars.1 Release (4.5.1)

I use the plugin refactoring tool "PHP Development Tools 3.6" to rename, for example. classes.

Our class file names follow the simple PSR-0 convention that underscores are subdirectories.

So, for example, Class_Something Class is in /Something.php Class

If I rename the Class_Something class to Class_Something2, it would be great if the file automatically moved to Class / Something2.php

Does anyone know if automatic refactoring of not only the class name and links, but also the file name is possible?

Thanks in advance for your help!

Ben

+5
source share
1 answer

A handmade solution that looks like an Eclipse plugin

First download and install PHP Parser from: php-parser-github a simple example will show you that you can get the class name from the given source code

Source code example

require 'vendor/autoload.php'; use PhpParser\ParserFactory; $parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7); try { $stmts = $parser->parse('<?php class MyClass_SubDir {private $member;}'); var_dump($stmts); } catch (Error $e) { echo 'Parse Error: ', $e->getMessage(); } 

Starting from the command line // Exit

 array(1) { [0]=> object(PhpParser\Node\Stmt\Class_)#8 (6) { ["type"]=> int(0) ["extends"]=> NULL ["implements"]=> array(0) { } ["name"]=> string(14) "MyClass_SubDir" ["stmts"]=> array(1) { [0]=> object(PhpParser\Node\Stmt\Property)#7 (3) { ... } 

and, as you can see, we can get all the classes that are defined in the current source

 --object(PhpParser\Node\Stmt\Class_ | |___ name : MyClass_SubDir 

Goals here

  • extract the directory name from the class name to do this, you can use `regex` or` explode`
  • Move the current file to the desired directory, you can use the `rename` function

Save your PHP code somewhere ... eclipse_plugin.php, for example ..

The next step is to create a batch file that will be connected to Eclipse

Create a bath file in which it will receive 2 arguments from Eclipse

  • ** $ 1 **: container location - the absolute path to the selected file in Eclipse
  • ** $ 2 **: resource location - the absolute path and name of the selected file in Eclipse (we only need $ 2 :-))

In the batch file, put

 php eclipse_plugin.php $1 $2 

Note : php must be in PATH environment variables PHP will find its arguments in $argv[0] and $argv[1]

Configure Eclipse

  • go to the section "Launching external tools"> "Configuration of external tools"> click "Program section"> "Click the new launch configuration"
  • in the Main tab, specify the location of your custom batch file
  • Also indicate its working directory
  • in the Arguments section, put these arguments $ {container_loc} $ {resource_loc}

Done! , now when you rename your class to Eclipse, just click the Start button :)

NTN

+4
source

Source: https://habr.com/ru/post/1240594/


All Articles