Scaffolding the Parser Implementation

Learn how to replace complicated structures with spaces and newlines.

We will apply many of the concepts and techniques we have discussed so far in this course to develop a Laravel Blade validation system. Our validator will only be concerned with directives and their parameters, and these limitations will allow us to take a few shortcuts and dramatically simplify our validator implementation. Instead of diving headfirst into our validator, let’s take some time to explore some of the situations we will detect with our validator.

The main set of issues we will be detecting are related to directive arguments. The first will be directives missing required argument groups and argument groups being present on those that should not have argument groups. An example of this is shown below, where the @foreach directive is missing all of its argument group, and the @endforeach directive has one where it is not necessary:

@foreach

@endforeach ($users as $user)

The next type of issue we will detect is when an argument group starts on the line following the directive name, which will cause invalid PHP code when the template is compiled:

@if
    (5 > 3)


@endif

Thirdly, we will also provide ways to enforce the casing of directive names as well as the spacing between a directive’s name and its argument group:

@FOREACH     ($users as $user)


@ENDFOREACH

Admittedly, the last group of items to validate does not necessarily produce compiler errors, but it will provide us an opportunity to have some fun with our validator.

Example of Blade complexity

We now need to start thinking about what we will parse. While our end goal is to validate Blade directives, there are several potential issues that we need to think through before we start writing our parser. For example, the code below provides an example Blade template that contains raw PHP blocks, Blade comments, some verbatim blocks, as well as some PHP code all mixed together:

Get hands-on with 1200+ tech skills courses.