regexsymfonynelmioapidocbundle

NelmioApiDocBundle negative path_patterns


Right now I try to create an API documentation in Symfony 3 with the NelmioApiDocBundle. So far everything works as described in the given symfony documentation.

Now I'd like to remove the _error and _profiler routes from the swagger docs. It says you can just use path_patterns. So I need to write down all routes there which I need in the documentation. But I have quite some different pathes.

It would be cool to have the opportunity to create negative path patterns like

...
    path_patterns:
        - !^/_error
        - !^/fubar

Is something like that possible?


Solution

  • Those are regex patterns so, yes you should be able to match any kind of pattern regex allows.
    Check out "lookaround" zero-length assertions, specifically a Negative lookahead, and try something like below:

    path_patterns:
        - ^\/((?!_error)(?!fubar).)*$
    

    Regex101 is an excellent tool for testing and understanding your regex. It will explain the impact of every part of the regex like so:

    ^ asserts position at start of a line
    \/ matches the character / literally (case sensitive)
    1st Capturing Group ((?!_error)(?!fubar).)*
    * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data
    Negative Lookahead (?!_error)
    Assert that the Regex below does not match
    _error matches the characters _error literally (case sensitive)
    Negative Lookahead (?!fubar)
    Assert that the Regex below does not match
    fubar matches the characters fubar literally (case sensitive)
    . matches any character (except for line terminators)
    $ asserts position at the end of a line