Passed
Push — main ( 80f8ac...067329 )
by Thomas
02:37
created

Sections::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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