-
-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathPhpIfElement.php
More file actions
91 lines (72 loc) · 2.03 KB
/
PhpIfElement.php
File metadata and controls
91 lines (72 loc) · 2.03 KB
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
<?php
declare(strict_types=1);
namespace Tempest\View\Elements;
use Tempest\View\Element;
use Tempest\View\Exceptions\ElementWasInvalid;
use Tempest\View\WrapsElement;
final class PhpIfElement implements Element, WrapsElement
{
use IsElement;
private ?Element $else = null;
/** @var Element[] */
private array $elseif = [];
public function __construct(
private readonly Element $wrappingElement,
) {}
public function getWrappingElement(): Element
{
return $this->wrappingElement;
}
public function addElseif(Element $element): self
{
$this->elseif[] = $element;
return $this;
}
public function setElse(Element $element): self
{
if ($this->else !== null) {
throw new ElementWasInvalid('There can only be one else element.');
}
$this->else = $element;
return $this;
}
public function compile(): string
{
if ($condition = $this->wrappingElement->consumeAttribute(':isset')) {
$condition = preg_replace('/\$\w+/', 'isset($0)', $condition);
} else {
$condition = $this->wrappingElement->consumeAttribute(':if');
}
$compiled = sprintf(
'<?php if(%s): ?>
%s',
$condition,
$this->wrappingElement->compile(),
);
foreach ($this->elseif as $elseif) {
$compiled = sprintf(
'%s
<?php elseif(%s): ?>
%s',
$compiled,
$elseif->consumeAttribute(':elseif'),
$elseif->compile(),
);
}
if ($this->else !== null) {
$this->else->consumeAttribute(':else');
$compiled = sprintf(
'%s
<?php else: ?>
%s',
$compiled,
$this->else->compile(),
);
}
return sprintf(
'%s
<?php endif; ?>',
$compiled,
);
}
}