Sublime Text snippet to insert PSR-0 namespace

梦想与她 提交于 2019-12-06 13:43:54

Here is a namespace substitution that works at 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;

I did manage to get it working, but it is sadly limited to a specified number of namespace-levels. Since my current project always has 2 levels (Project\Namespace) it works well for now. But it is not the optimal solution.

Here is the regex:

(?:^.*src\/|\G)(.*?)\/(.*?)\/(?:.*php|\G)
  1. Non capturing selection of everything up to src/
  2. Select everything to next /. ("Namespace")
  3. Do step 2 again. ("Subnamespace")
  4. Non capturing selection of the filename

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

The full snippet-ready version is:

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

This will output Namespace\Subnamespace.

It works for now, but I would very much like to see a version that works for any number of namespace levels.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!