Newer
Older

Yassine Doghri
committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
<?php
declare(strict_types=1);
namespace ViewComponents;
use RuntimeException;
use ViewComponents\Config\ViewComponents;
/**
* Borrowed and adapted from https://github.com/lonnieezell/Bonfire2/
*/
class ComponentRenderer
{
protected ViewComponents $config;
/**
* File name of the view source
*/
protected string $currentView;
public function __construct()
{
$this->config = config('ViewComponents');
}
public function setCurrentView(string $view): self
{
$this->currentView = $view;
return $this;
}
public function render(string $output): string
{
// Try to locate any custom tags, with PascalCase names like: Button, Label, etc.
service('timer')
->start('self-closing');
$output = $this->renderSelfClosingTags($output);
service('timer')
->stop('self-closing');
service('timer')
->start('paired-tags');
$output = $this->renderPairedTags($output);
service('timer')
->stop('paired-tags');
return $output;
}
/**
* Finds and renders self-closing tags, i.e. <Foo />
*/
private function renderSelfClosingTags(string $output): string
{
// Pattern borrowed and adapted from Laravel's ComponentTagCompiler
// Should match any Component tags <Component />
$pattern = "/
<
\s*
(?<name>[A-Z][A-Za-z0-9\.]*?)
\s*
(?<attributes>
(?:
\s+
(?:
(?:
\{\{\s*\\\$attributes(?:[^}]+?)?\s*\}\}
)
|
(?:
[\w\-:.@]+
(
=
(?:
\\\"[^\\\"]*\\\"
|
\'[^\']*\'
|
[^\'\\\"=<>]+
)
)?
)
)
)*
\s*
)
\/>
/x";
/*
$matches[0] = full tags matched
$matches[name] = tag name
$matches[attributes] = array of attribute string (class="foo")
*/
return preg_replace_callback($pattern, function ($match): string {
$view = $this->locateView($match['name']);
$attributes = $this->parseAttributes($match['attributes']);
$component = $this->factory($match['name'], $view, $attributes);
return $component instanceof Component
? $component->render()
: $this->renderView($view, $attributes);
}, $output) ?? '';
}
private function renderPairedTags(string $output): string
{
$pattern = '/<\s*(?<name>[A-Z][A-Za-z0-9\.]*?)(?<attributes>[\s\S\=\'\"]*)>(?<slot>.*)<\/\s*\1\s*>/uUsm';
/*
$matches[0] = full tags matched and all of its content
$matches[name] = pascal cased tag name
$matches[attributes] = string of tag attributes (class="foo")
$matches[slot] = the content inside the tags
*/
return preg_replace_callback($pattern, function ($match): string {
$view = $this->locateView($match['name']);
$attributes = $this->parseAttributes($match['attributes']);
$attributes['slot'] = $match['slot'];
$component = $this->factory($match['name'], $view, $attributes);
return $component instanceof Component
? $component->render()
: $this->renderView($view, $attributes);
}, $output) ?? (string) preg_last_error();
}
/**
* Locate the view file used to render the component. The file's name must match the name of the component.
*
* Looks for class and view file components in the current module before checking the default app module
*/
private function locateView(string $name): string
{
// TODO: Is there a better way to locate components local to current module?
$pathsToDiscover = [];
$lookupPaths = $this->config->lookupPaths;
$pathsToDiscover = array_filter($lookupPaths, function ($path): bool {
return str_starts_with($this->currentView, $path);
});
$pathsToDiscover = array_values($pathsToDiscover);
$pathsToDiscover[] = $this->config->defaultLookupPath;

Yassine Doghri
committed
$namePath = str_replace('.', '/', $name);
foreach ($pathsToDiscover as $basePath) {

Yassine Doghri
committed
// Look for a class component first
$filePath = $basePath . $this->config->componentsDirectory . '/' . $namePath . '.php';

Yassine Doghri
committed
if (is_file($filePath)) {
return $filePath;
}
$snakeCaseName = strtolower(preg_replace('~(?<!^)(?<!\/)[A-Z]~', '_$0', $namePath) ?? '');
$filePath = $basePath . $this->config->componentsDirectory . '/' . $snakeCaseName . '.php';

Yassine Doghri
committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
if (is_file($filePath)) {
return $filePath;
}
}
throw new RuntimeException("View not found for component: {$name}");
}
/**
* Parses a string to grab any key/value pairs, HTML attributes.
*
* @return array<string, string>
*/
private function parseAttributes(string $attributeString): array
{
// Pattern borrowed from Laravel's ComponentTagCompiler
$pattern = '/
(?<attribute>[\w\-:.@]+)
(
=
(?<value>
(
\"[^\"]+\"
|
\'[^\']+\'
|
\\\'[^\\\']+\\\'
|
[^\s>]+
)
)
)?
/x';
if (! preg_match_all($pattern, $attributeString, $matches, PREG_SET_ORDER)) {
return [];
}
$attributes = [];
/**
* @var array<string, string> $match
*/
foreach ($matches as $match) {
$attributes[$match['attribute']] = $this->stripQuotes($match['value']);
}
return $attributes;
}
/**
* Attempts to locate the view and/or class that will be used to render this component. By default, the only thing
* that is needed is a view, but a Component class can also be found if more power is needed.
*
* If a class is used, the name is expected to be <viewName>Component.php
*
* @param array<string, mixed> $attributes
*/
private function factory(string $name, string $view, array $attributes): ?Component
{
// Locate the class in the same folder as the view
$class = $name . '.php';
$filePath = str_replace($name . '.php', $class, $view);
if ($filePath === '') {
return null;
}
if (! file_exists($filePath)) {
return null;
}
$className = service('locator')
->getClassname($filePath);
/** @phpstan-ignore-next-line */
if (! class_exists($className)) {
return null;
}
return new $className($attributes);
}
/**
* Renders the view when no corresponding class has been found.
*
* @param array<string, string> $data
*/
private function renderView(string $view, array $data): string
{
return (function (string $view, $data): string {
/** @phpstan-ignore-next-line */
extract($data);
ob_start();
eval('?>' . file_get_contents($view));
return ob_get_clean() ?: '';
})($view, $data);
}
/**
* Removes surrounding quotes from a string.
*/
private function stripQuotes(string $string): string
{
return trim($string, "\'\"");
}
}