Skip to content

Commit 0bb9cf7

Browse files
authored
feat: templator boolean (#418)
1 parent ce28557 commit 0bb9cf7

File tree

4 files changed

+47
-0
lines changed

4 files changed

+47
-0
lines changed

src/System/View/Templator.php

+2
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace System\View;
66

7+
use System\View\Templator\BooleanTemplator;
78
use System\View\Templator\BreakTemplator;
89
use System\View\Templator\CommentTemplator;
910
use System\View\Templator\ComponentTemplator;
@@ -156,6 +157,7 @@ public function templates(string $template): string
156157
BreakTemplator::class,
157158
UseTemplator::class,
158159
JsonTemplator::class,
160+
BooleanTemplator::class,
159161
], function (string $template, string $templator): string {
160162
$templator = new $templator($this->finder, $this->cacheDir);
161163
if ($templator instanceof IncludeTemplator) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace System\View\Templator;
6+
7+
use System\View\AbstractTemplatorParse;
8+
9+
final class BooleanTemplator extends AbstractTemplatorParse
10+
{
11+
public function parse(string $template): string
12+
{
13+
return preg_replace_callback(
14+
'/{%\s*bool\(\s*(.+?)\s*\)\s*%}/',
15+
static fn (array $matches): string => "<?= ({$matches[1]}) ? 'true' : 'false' ?>",
16+
$template
17+
);
18+
}
19+
}

src/System/View/Templator/DirectiveTemplator.php

+1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ class DirectiveTemplator extends AbstractTemplatorParse
2929
'foreach' => EachTemplator::class,
3030
'if' => IfTemplator::class,
3131
'include' => IncludeTemplator::class,
32+
'bool' => BooleanTemplator::class,
3233
'json' => JsonTemplator::class,
3334
'php' => PHPTemplator::class,
3435
'raw' => NameTemplator::class,

tests/View/Templator/BooleanTest.php

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace System\Test\View\Templator;
6+
7+
use PHPUnit\Framework\TestCase;
8+
use System\View\Templator;
9+
use System\View\TemplatorFinder;
10+
11+
final class BooleanTest extends TestCase
12+
{
13+
/**
14+
* @test
15+
*/
16+
public function itCanRenderBoolean()
17+
{
18+
$templator = new Templator(new TemplatorFinder([__DIR__], ['']), __DIR__);
19+
$out = $templator->templates('<input x-enable="{% bool(1 == 1) %}">');
20+
$this->assertEquals(
21+
'<input x-enable="<?= (1 == 1) ? \'true\' : \'false\' ?>">',
22+
$out
23+
);
24+
}
25+
}

0 commit comments

Comments
 (0)