Search⌘ K
AI Features

Solution: Parsing Blade Echos

Explore how to enhance a Laravel Blade directive validator to parse Blade echo tags correctly. Learn to extract dynamic content between curly braces while handling nested strings, ensuring accurate template parsing in Blade views.

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:

PHP
<?php
class 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:

PHP
<?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: 7
    endPosition: 17
    length: 11
    value: "{{ $name }}"
   
...