|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Mauricius\LaravelHtmx\View; |
| 6 | + |
| 7 | +class BladeFragmentParser |
| 8 | +{ |
| 9 | + public function __construct(private string $openDirective, private string $closeDirective) |
| 10 | + { |
| 11 | + } |
| 12 | + |
| 13 | + /** |
| 14 | + * @param string $content |
| 15 | + * @return CloseFragmentElement[]|OpenFragmentElement[] |
| 16 | + */ |
| 17 | + public function parse(string $content): array |
| 18 | + { |
| 19 | + $content = $this->normalizeLineEndings($content); |
| 20 | + |
| 21 | + return $this->prepareNodeList($content); |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * @param string $content |
| 26 | + * @return array<OpenFragmentElement|CloseFragmentElement> |
| 27 | + */ |
| 28 | + private function prepareNodeList(string $content): array |
| 29 | + { |
| 30 | + $re = sprintf('/(?<!@)@%s[ \t]*\([\'"](.+?)[\'"]\)|@%s/', $this->openDirective, $this->closeDirective); |
| 31 | + |
| 32 | + preg_match_all($re, $content, $matches, PREG_SET_ORDER|PREG_OFFSET_CAPTURE); |
| 33 | + |
| 34 | + if (! is_array($matches) || count($matches) < 2) { |
| 35 | + return []; |
| 36 | + } |
| 37 | + |
| 38 | + $lastOffset = 0; |
| 39 | + |
| 40 | + /** @var array $nodes */ |
| 41 | + $nodes = array_map(function (array $match) use ($content, &$lastOffset) { |
| 42 | + // Convert regex offsets to multibyte offsets. |
| 43 | + $offset = $match[0][1]; |
| 44 | + |
| 45 | + if ($offset !== 0) { |
| 46 | + $offset = mb_strpos($content, $match[0][0], $lastOffset + 1); |
| 47 | + } |
| 48 | + |
| 49 | + if ($offset === false) { |
| 50 | + $offset = $match[0][1]; |
| 51 | + } |
| 52 | + |
| 53 | + $lastOffset = $offset + 1; |
| 54 | + |
| 55 | + if (str_starts_with($match[0][0], sprintf('@%s', $this->openDirective))) { |
| 56 | + $openElement = new OpenFragmentElement(); |
| 57 | + $openElement->name = $match[1][0]; |
| 58 | + $openElement->startOffset = $offset; |
| 59 | + $openElement->endOffset = $offset + mb_strlen($match[0][0]); |
| 60 | + |
| 61 | + return $openElement; |
| 62 | + } |
| 63 | + |
| 64 | + if (str_starts_with($match[0][0], sprintf('@%s', $this->closeDirective))) { |
| 65 | + $closeElement = new CloseFragmentElement(); |
| 66 | + $closeElement->startOffset = $offset; |
| 67 | + $closeElement->endOffset = $offset + mb_strlen($match[0][0]); |
| 68 | + |
| 69 | + return $closeElement; |
| 70 | + } |
| 71 | + |
| 72 | + return null; |
| 73 | + }, $matches); |
| 74 | + |
| 75 | + return array_filter($nodes); |
| 76 | + } |
| 77 | + |
| 78 | + private function normalizeLineEndings(string $content): string |
| 79 | + { |
| 80 | + return str_replace(['\r\n', '\r'], '\n', $content); |
| 81 | + } |
| 82 | +} |
0 commit comments