Skip to content

Instantly share code, notes, and snippets.

@ericclemmons
Created July 13, 2012 03:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericclemmons/3102439 to your computer and use it in GitHub Desktop.
Save ericclemmons/3102439 to your computer and use it in GitHub Desktop.
Automatically generate the namespace & class depending on where the file is saved
<!--
File is located at:
/Users/Eric/Sites/MyApp/src/MyApp/Bundle/BlogBundle/Entity/Blog/Post.php
Problem:
No way to double-substitute or chain filters
Expected Output:
namespace MyApp\Bundle\BlogBundle\Entity\Blog;
class Post
{
}
Actual Output:
namespace MyApp/Bundle/BlogBundle/Entity/Blog;
class Post
{
}
-->
<snippet>
<content><![CDATA[
namespace ${TM_FILEPATH/^.+\/[a-z]+\/([\w\/]+)\/\w+\.php$/$1/};
class ${TM_FILENAME/^([\w\/]+)\.php$/$1/}
{
${0}
}
]]></content>
<tabTrigger>namespace</tabTrigger>
<scope>source.php</scope>
</snippet>
@Corben78
Copy link

I had a similar problem, and finally I managed to solve it. For you it should look like this:

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

For me using Laravel, the path is /home/user/git/laravel-project/app/... and should be replaced by App:

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

I've taken the solution from Sublime Text snippet to insert PSR-0 namespace and adjusted it just a little bit.

The substitution for the classname could also be done a little bit shorter (just strip the .php suffix):

class ${TM_FILENAME/\.php$//}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment