Sublime Text snippet to insert PSR-0 namespace

I am trying to make a Sublime Text fragment that inserts a PHP template class in lines:

<?php namespace Namespace\Subnamespace; class TestClass { public function __construct() { //code... } } 

When using PHP-FIG standards (or similar), both the namespace and the class name can be obtained from the file path. The file in the above example will be placed in /Users/Projects/Whatever/src/Namespace/Subnamespace/TestClass.php .

This is what I have so far:

 <snippet> <content><![CDATA[ <?php namespace ${1:Namespace}; class ${TM_FILENAME/(.*)[.](.*)/$1/g} { public function __construct() { ${0://code...} } } ]]></content> <tabTrigger>phpclass</tabTrigger> <scope>text.html</scope> </snippet> 

I already figured out how to get the class name, but getting the namespace turned out to be a lot harder. I am far from a regular expression expert, and this requires:

  • Getting everything after src/
  • ... and to the last /
  • Flip all other slashes to backslashes.

/Users/Projects/Whatever/src/Namespace/Subnamespace/TestClass.php becomes Namespace\Subnamespace .

This is the most relevant thread that I found on this issue, but it is a way above my head, and I could not even get it to work.

Can anyone help me with this?

+2
source share
2 answers

Here is a namespace lookup that works on more than 2 levels in ST-3:

namespace ${1:${TM_FILEPATH/(?:.*src\/)|(\/)?([^\/]+)(?=\/)|(?:\/[^\/]+\.php$)/(?1:\\$^N:$^N)/g}};

file: /path/to/project/src/sub1/sub2/sub3/sub4/class.php

output: namespace sub1\sub2\sub3\sub4;

+2
source

I managed to get it to work, but it is, unfortunately, limited to the specified number of levels of the namespace. Since my current project always has 2 levels ( Project\Namespace ), it works well. But this is not an optimal solution.

Here is the regex:

 (?:^.*src\/|\G)(.*?)\/(.*?)\/(?:.*php|\G) 
  • Doesn't commit the selection of everything up to src/
  • Select All to Skip to the Next / . ("Namespace")
  • Repeat step 2. ("Subspace Names")
  • Do not commit file name selection

Then I will replace with $1\\$2 , which places the captures from step 2 and 3 with a backslash between.

Full version of the finished fragment:

 ${TM_FILEPATH/(?:^.*src\/|\G)(.*?)\/(.*?)\/(?:.*php|\G)/$1\\$2/g} 

This will exit Namespace\Subnamespace .

Now it works, but I really would like to see a version that works for any number of levels of the namespace.

0
source

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


All Articles