Solution: Parsing Blade Echos
Learn about how to parse Blade echos by refactoring the parse class.
We'll cover the following...
Problem statement
Our validator parser currently only handles Blade directives. How might you refactor this parser to be able to parse Blade echos, such as {{ $title }}
?
Solution
The simplest implementation to extract all regions between a pair of curly braces would be the following:
Press + to interact
<?phpclass BladeEchoCursor extends AbstractStringCursor{public function accept(string $current, ?string $prev = null, ?string $next = null): ?bool{if ($current == '}' && $prev == '}') {return $this->break();}return $this->continue();}}
We can use our new implementation like so:
Press + to interact
<?php$input = <<<'BLADE'Hello, {{ $name }}! The time is {{ now() }}.BLADE;$string = new Utf8StringIterator($input);$echos = [];foreach ($string as $char) {if ($char == '{') {$cursor = new BladeEchoCursor($string);$echos[] = $cursor->traverse();continue;}}
This would result in output similar to the following:
array [
0 => CursorResult {
startPosition:
...