|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\BladeX; |
|
4
|
|
|
|
|
5
|
|
|
use SimpleXMLElement; |
|
6
|
|
|
|
|
7
|
|
|
class BladeXCompiler |
|
8
|
|
|
{ |
|
9
|
|
|
/** @var \Spatie\BladeX\BladeX */ |
|
10
|
|
|
protected $bladeX; |
|
11
|
|
|
|
|
12
|
|
|
public function __construct(BladeX $bladeX) |
|
13
|
|
|
{ |
|
14
|
|
|
return $this->bladeX = $bladeX; |
|
|
|
|
|
|
15
|
|
|
} |
|
16
|
|
|
|
|
17
|
|
|
public function compile(string $viewContents): string |
|
18
|
|
|
{ |
|
19
|
|
|
return array_reduce( |
|
20
|
|
|
$this->bladeX->getRegisteredComponents(), |
|
21
|
|
|
[$this, 'parseComponentHtml'], |
|
22
|
|
|
$viewContents); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
protected function parseComponentHtml(string $viewContents, BladeXComponent $bladeXComponent) |
|
26
|
|
|
{ |
|
27
|
|
|
$pattern = "/<\s*{$bladeXComponent->name}[^>]*>((.|\n)*?)<\s*\/\s*{$bladeXComponent->name}>/m"; |
|
28
|
|
|
|
|
29
|
|
|
return preg_replace_callback($pattern, function (array $regexResult) use ($bladeXComponent) { |
|
30
|
|
|
[$componentHtml, $componentInnerHtml] = $regexResult; |
|
|
|
|
|
|
31
|
|
|
|
|
32
|
|
|
return "@component('{$bladeXComponent->bladeViewName}', [{$this->getComponentAttributes($componentHtml)}])" |
|
33
|
|
|
. $this->parseComponentInnerHtml($componentInnerHtml) |
|
34
|
|
|
. '@endcomponent'; |
|
35
|
|
|
}, $viewContents); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
protected function getComponentAttributes(string $componentHtml): string |
|
39
|
|
|
{ |
|
40
|
|
|
$componentXml = new SimpleXMLElement($componentHtml); |
|
41
|
|
|
|
|
42
|
|
|
return collect($componentXml->attributes()) |
|
43
|
|
|
->map(function ($value, $attribute) { |
|
44
|
|
|
$value = str_replace("'", "\\'", $value); |
|
45
|
|
|
|
|
46
|
|
|
return "'{$attribute}' => '{$value}',"; |
|
47
|
|
|
})->implode(''); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
protected function parseComponentInnerHtml(string $componentInnerHtml): string |
|
51
|
|
|
{ |
|
52
|
|
|
$pattern = '/<\s*slot[^>]*name=[\'"](.*)[\'"][^>]*>((.|\n)*?)<\s*\/\s*slot>/m'; |
|
53
|
|
|
|
|
54
|
|
|
return preg_replace_callback($pattern, function ($result) { |
|
55
|
|
|
[$slot, $name, $contents] = $result; |
|
|
|
|
|
|
56
|
|
|
|
|
57
|
|
|
return "@slot('{$name}'){$contents}@endslot"; |
|
58
|
|
|
}, $componentInnerHtml); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|