|
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
|
|
|
foreach ($this->bladeX->getRegisteredComponents() as $componentName => $viewPath) { |
|
20
|
|
|
$viewContents = $this->replaceBladeXComponentWithRegularBladeComponent($viewContents, $componentName, $viewPath); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
return $viewContents; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
protected function replaceBladeXComponentWithRegularBladeComponent(string $viewContents, $bladeXComponentName, string $bladeViewPath) |
|
27
|
|
|
{ |
|
28
|
|
|
$pattern = '/<\s*' . $bladeXComponentName . '[^>]*>((.|\n)*?)<\s*\/\s*' . $bladeXComponentName . '>/m'; |
|
29
|
|
|
|
|
30
|
|
|
$viewContents = preg_replace_callback($pattern, function (array $regexResult) use ($bladeViewPath) { |
|
31
|
|
|
[$componentHtml, $componentInnerHtml] = $regexResult; |
|
|
|
|
|
|
32
|
|
|
|
|
33
|
|
|
return "@component('{$bladeViewPath}', [{$this->getComponentAttributes($componentHtml)}])" |
|
34
|
|
|
. $this->parseComponentInnerHtml($componentInnerHtml) |
|
35
|
|
|
. '@endcomponent'; |
|
36
|
|
|
}, $viewContents); |
|
37
|
|
|
return $viewContents; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
protected function getComponentAttributes(string $componentHtml): string |
|
41
|
|
|
{ |
|
42
|
|
|
$componentXml = new SimpleXMLElement($componentHtml); |
|
43
|
|
|
|
|
44
|
|
|
return collect($componentXml->attributes()) |
|
45
|
|
|
->map(function ($value, $attribute) { |
|
46
|
|
|
$value = str_replace("'", "\\'", $value); |
|
47
|
|
|
|
|
48
|
|
|
return "'{$attribute}' => '{$value}',"; |
|
49
|
|
|
})->implode(''); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
protected function parseComponentInnerHtml(string $componentInnerHtml): string |
|
53
|
|
|
{ |
|
54
|
|
|
$pattern = '/<\s*slot[^>]*name=[\'"](.*)[\'"][^>]*>((.|\n)*?)<\s*\/\s*slot>/m'; |
|
55
|
|
|
|
|
56
|
|
|
return preg_replace_callback($pattern, function ($result) { |
|
57
|
|
|
[$slot, $name, $contents] = $result; |
|
|
|
|
|
|
58
|
|
|
|
|
59
|
|
|
return "@slot('{$name}'){$contents}@endslot"; |
|
60
|
|
|
}, $componentInnerHtml); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|