1. renders self close components without arguments

580-view-class-steroids
fadrian06 1 day ago
parent 576801967c
commit a94431ae05

@ -92,6 +92,17 @@ class View
* @throws Exception If template not found
*/
public function render(string $file, ?array $templateData = null): void
{
echo $this->fetch($file, $templateData);
}
/**
* Gets the output of a template
* @param string $file Template file
* @param ?array<string, mixed> $data Template data
* @return string Output of template
*/
public function fetch(string $file, ?array $data = null): string
{
$template = $this->getTemplate($file);
@ -101,30 +112,26 @@ class View
extract($this->vars);
if (is_array($templateData)) {
extract($templateData);
if (is_array($data)) {
extract($data);
if ($this->preserveVars) {
$this->vars += $templateData;
$this->vars += $data;
}
}
include $template;
}
/**
* Gets the output of a template
* @param string $file Template file
* @param ?array<string, mixed> $data Template data
* @return string Output of template
*/
public function fetch(string $file, ?array $data = null): string
{
ob_start();
include $template;
$view = ob_get_clean();
preg_match('/<f-(?<component>[a-z-]+)\s*\/>/', $view, $matches);
$this->render($file, $data);
if ($matches) {
$tag = $matches[0];
$component = $this->fetch("components/{$matches['component']}");
$view = str_replace($tag, $component, $view);
}
return ob_get_clean();
return $view;
}
/**

@ -234,6 +234,32 @@ class ViewTest extends TestCase
];
}
/** @dataProvider pagesDataProvider */
public function testItRendersComponent(string $page, string $expected): void
{
$view = new View(__DIR__ . '/views');
$view->preserveVars = false;
$actual = $view->fetch($page);
self::assertSame(self::removeLineEndings($expected), self::removeLineEndings($actual));
}
public static function pagesDataProvider(): array
{
return [
['pages/page-with-component-with-old-syntax', <<<'html'
<body>
value
</body>
html],
['pages/page-with-component-with-new-syntax', <<<'html'
<body>
value
</body>
html],
];
}
private static function removeLineEndings(string $subject): string
{
return str_replace(["\r", "\n"], '', $subject);

@ -0,0 +1,3 @@
<body>
<f-my-component />
</body>

@ -0,0 +1,3 @@
<body>
<?php $this->render('components/my-component') ?>
</body>
Loading…
Cancel
Save