|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Conia\Boiler; |
|
6
|
|
|
|
|
7
|
|
|
use Conia\Boiler\Exception\LogicException; |
|
8
|
|
|
|
|
9
|
|
|
class Sections |
|
10
|
|
|
{ |
|
11
|
|
|
/** @var array<string, Section> */ |
|
12
|
|
|
protected array $sections = []; |
|
13
|
|
|
|
|
14
|
|
|
protected array $capture = []; |
|
15
|
|
|
protected SectionMode $sectionMode = SectionMode::Closed; |
|
16
|
|
|
|
|
17
|
3 |
|
public function begin(string $name): void |
|
18
|
|
|
{ |
|
19
|
3 |
|
$this->open($name, SectionMode::Assign); |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
2 |
|
public function append(string $name): void |
|
23
|
|
|
{ |
|
24
|
2 |
|
$this->open($name, SectionMode::Append); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
2 |
|
public function prepend(string $name): void |
|
28
|
|
|
{ |
|
29
|
2 |
|
$this->open($name, SectionMode::Prepend); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
4 |
|
public function end(): void |
|
33
|
|
|
{ |
|
34
|
4 |
|
$content = ob_get_clean(); |
|
35
|
4 |
|
$name = (string)array_pop($this->capture); |
|
36
|
|
|
|
|
37
|
4 |
|
$this->sections[$name] = match ($this->sectionMode) { |
|
38
|
4 |
|
SectionMode::Assign => new Section($content), |
|
39
|
4 |
|
SectionMode::Append => ($this->sections[$name] ?? new Section(''))->append($content), |
|
40
|
4 |
|
SectionMode::Prepend => ($this->sections[$name] ?? new Section(''))->prepend($content), |
|
41
|
4 |
|
SectionMode::Closed => throw new LogicException('No section started'), |
|
42
|
4 |
|
}; |
|
43
|
|
|
|
|
44
|
3 |
|
$this->sectionMode = SectionMode::Closed; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
2 |
|
public function get(string $name): string |
|
48
|
|
|
{ |
|
49
|
2 |
|
return $this->sections[$name]->get(); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
2 |
|
public function getOr(string $name, string $default): string |
|
53
|
|
|
{ |
|
54
|
2 |
|
$section = $this->sections[$name] ?? null; |
|
55
|
|
|
|
|
56
|
2 |
|
if (is_null($section)) { |
|
57
|
1 |
|
return $default; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
1 |
|
if ($section->empty()) { |
|
61
|
1 |
|
$section->setValue($default); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
1 |
|
return $section->get(); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
2 |
|
public function has(string $name): bool |
|
68
|
|
|
{ |
|
69
|
2 |
|
return isset($this->sections[$name]); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
4 |
|
protected function open(string $name, SectionMode $mode): void |
|
73
|
|
|
{ |
|
74
|
4 |
|
if ($this->sectionMode !== SectionMode::Closed) { |
|
75
|
1 |
|
throw new LogicException('Nested sections are not allowed'); |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
4 |
|
$this->sectionMode = $mode; |
|
79
|
4 |
|
$this->capture[] = $name; |
|
80
|
4 |
|
ob_start(); |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|