Skip to content

Commit

Permalink
Added method to obtain list of template variables
Browse files Browse the repository at this point in the history
Signed-off-by: Erika Heidi <[email protected]>
  • Loading branch information
erikaheidi committed Jun 21, 2022
1 parent 6be1f26 commit a328319
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 9 deletions.
37 changes: 29 additions & 8 deletions src/Stencil.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,39 @@ public function __construct(string $stencilDir)
*/
public function applyTemplate(string $templateName, array $variables = []): string
{
$templateFile = $this->stencilDir . '/' . $templateName . '.tpl';

if (!is_file($templateFile)) {
throw new FileNotFoundException("Template file not found.");
}

$template = file_get_contents($templateFile);

$template = $this->getTemplate($templateName);
foreach ($variables as $variableName => $variableValue) {
$template = str_replace("{{ $variableName }}", $variableValue, $template);
}

return $template;
}

/**
* @param string $templateName
* @return mixed
* @throws FileNotFoundException
*/
public function scanTemplateVars(string $templateName): array
{
$template = $this->getTemplate($templateName);
preg_match_all('/\{\{\s([a-zA-z0-9-_]*\b)\s}}/', $template, $out);
return $out[1];
}

/**
* @param string $template
* @return string
* @throws FileNotFoundException
*/
public function getTemplate(string $template): string
{
$templateFile = $this->stencilDir . '/' . $template . '.tpl';

if (!is_file($templateFile)) {
throw new FileNotFoundException("Template file not found.");
}

return file_get_contents($templateFile);
}
}
12 changes: 11 additions & 1 deletion tests/StencilTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,18 @@
];

$parsedContent = $stencil->applyTemplate('mytemplate', $values);
var_dump($parsedContent);

expect($parsedContent)->toBeString();
$this->assertStringContainsString($values['name'], $parsedContent);
$this->assertStringContainsString($values['description'], $parsedContent);
});

it('obtains list of template variables', function () {
$stencil = getStencil();
$variables = $stencil->scanTemplateVars('mytemplate');

expect($variables)
->toBeArray()
->toContain('name')
->toContain('description');
});

0 comments on commit a328319

Please sign in to comment.