'How can I create a VSCode snippet to automatically insert namespace of files inside my src folder?

First off, I have the following psr-4 declaration for the src folder inside my composer.json file:

"autoload": {
        "psr-4": {
            "Src\\": "src/"
        }
    },

I would like to build a VSCode snippet that autogenerates the namespace of a new file that resides inside the src folder.

So far I have this inside php.json:

    "Namespace Src": {
        "prefix": "ns_src",
        "body": [
            "namespace ${RELATIVE_FILEPATH};",
        ],
        "description": "Namespace for file routes inside the src folder"
    },

Taking as an example the following file:

src/MyEntity/Application/MyUseCase.php

The desired result would be:

namespace Src\MyEntity\Application;

And right now this is what it returns to me:

namespace src/MyEntity/Application/MyUseCase.php;

So I need to tackle:

  • Upper case of src.
  • Replacement of forward slashes / into back slashes \.
  • Removal of everything that is after the last forward slash /.

I know there has to be a way to do this with regex. I have read this similar problem (VSCODE snippet PHP to fill namespace automatically) but I haven't quite got the hang of it after reading it. And I think the upper case problem could maybe be solved with \F as in here: https://www.regular-expressions.info/replacecase.html#:~:text=In%20the%20regex%20%5CU%5Cw,is%20not%20a%20word%20character.

Is this the right approach? Could you give me any tips on this problem?

Thank you so much.



Solution 1:[1]


"Namespace Src": {
    "prefix": "ns_src",
    "body": [
      "namespace ${RELATIVE_FILEPATH/^(?:.*[\\\\\\/])?(src)(?=[\\\\\\/])|[\\\\\\/][^\\\\\\/]*$|([\\\\\\/])/${1:+Src}${2:+\\\\}/g};",

            // my version
      "namespace ${RELATIVE_FILEPATH/^([^\\\\\\/]+)|[\\\\\\/][^\\\\\\/]*$|([\\\\\\/])/${1:/capitalize}${2:+\\\\}/g};",
    ],
    "description": "Namespace for file routes inside the src folder"
}

Riffing off the other answer - this captures the leading directory and capitalizes it whatever it is called. Unclear whether you want it work for src folder only.

Leading directory: ([^\\\\\\/]+)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark