Parsing Blade Directives

Learn how to add more components to the blade directive validator.

Implementation of the BladeDirectiveValidator class

Our next task will be to set things up to extract information about any Blade directives that appear within our input text. In the previous chapter, we explored the idea of using a regular expression to help us build an index of where we should start looking for parseable items within a document. We will do the same for the Blade directives because this will help us avoid escaped Blade directives as well as things that look like directives that should be ignored, such as CSS media queries.

To do this, we will need a list of the core directive names and a way to provide a list of custom directives, which can be populated at runtime by retrieving them from the Blade compiler within the context of a running application. Once we have those items, we can construct a dynamic regular expression that is similar to the following:

/(?<!@)@(?!@)(can|cannot|canany)/i

The regular expression above begins with an obscure pattern. Still, it matches the @ character as long it is not followed or preceded by another instance of the @ character. We must account for both cases to avoid accidentally matching the first @ in an escaped Blade directive.

Get hands-on with 1200+ tech skills courses.