|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Sketch\Tpl; |
|
4
|
|
|
|
|
5
|
|
|
class Inheritance extends Content |
|
6
|
|
|
{ |
|
7
|
|
|
private $config; |
|
8
|
|
|
private $blocks = []; |
|
9
|
|
|
private $content = ''; |
|
10
|
|
|
private $patternBlock = '/{\s?block \'?"?([\w]+)"?\'?\s?}(.*?){\s?\/block\s?}/is'; |
|
11
|
|
|
private $patternExtends = '/{\s?extends \'?"?(.*?)"?\'?\s?}/is'; |
|
12
|
|
|
|
|
13
|
|
|
public function __construct(string $content, array $config) |
|
14
|
|
|
{ |
|
15
|
|
|
$this->config = $config; |
|
16
|
|
|
$this->content = $content; |
|
17
|
|
|
$this->block(); |
|
18
|
|
|
$this->extends(); |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
public function __toString(): string |
|
22
|
|
|
{ |
|
23
|
|
|
return $this->content; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
private function block(): void |
|
27
|
|
|
{ |
|
28
|
|
|
if (preg_match_all($this->patternBlock, $this->content, $matches, PREG_SET_ORDER)) { |
|
29
|
|
|
for ($i = 0; $i < count($matches); $i++) { |
|
|
|
|
|
|
30
|
|
|
$this->blocks[$matches[$i][1]] = $matches[$i][2]; |
|
31
|
|
|
$this->content = str_replace($this->blocks[$matches[$i][1]], '', $this->content); |
|
32
|
|
|
}; |
|
33
|
|
|
} |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
private function extends(): void |
|
37
|
|
|
{ |
|
38
|
|
|
if (preg_match($this->patternExtends, $this->content, $match)) { |
|
39
|
|
|
$this->content = $this->getContent($match[1], $this->config); |
|
40
|
|
|
$this->replace(); |
|
41
|
|
|
} |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
private function replace(): void |
|
45
|
|
|
{ |
|
46
|
|
|
foreach ($this->blocks as $key => $value) { |
|
47
|
|
|
$pattern = '/{\s?block \'?"?'.$key.'"?\'?\s?}(.*?){\s?\/block\s?}/is'; |
|
48
|
|
|
$this->content = preg_replace($pattern, $value, $this->content); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
$this->content = preg_replace('/{\s?block \'?"?[\w]+"?\'?\s?}/is', '', $this->content); |
|
52
|
|
|
$this->content = preg_replace('/{\s?\/block\s?}/is', '', $this->content); |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: