Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add snippets support #147

Merged
merged 10 commits into from
Jul 2, 2019
12 changes: 9 additions & 3 deletions code/site/components/com_pages/template/default.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,8 @@ public function invokeHelper($identifier, ...$params)
if(!empty($parts)) {
$identifier = implode('.', $parts).'.template.helper.'.$identifier;
}

$helper = $this->createHelper($identifier, $params);
$helper = $this->createHelper($identifier);

//Call the helper function
if (!is_callable(array($helper, $function))) {
Expand All @@ -121,7 +121,13 @@ public function invokeHelper($identifier, ...$params)
$params = array_merge($this->getParameters()->toArray(), $params);
}

return $helper->$function(...$params);
if(is_numeric(key($params))) {
$result = $helper->$function(...$params);
} else {
$result = $helper->$function($params);
}

return $result;
}

public function createHelper($helper, $config = array())
Expand Down
59 changes: 59 additions & 0 deletions code/site/components/com_pages/template/helper/snippet.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

class ComPagesTemplateHelperSnippet extends ComPagesTemplateHelperAbstract
{
private $__snippets = array();

public function __invoke($name, $snippet)
{
if(is_string($snippet)) {
$result = $this->define($name, $snippet);
} else {
$result = $this->expand($name, $snippet);
}

return $result;
}

public function define(string $name, string $snippet, $overwrite = false)
{
$result = false;

if(!isset($this->__snippets[$name]) || $overwrite)
{
$this->__snippets[$name] = $snippet;
$result = true;
}

return $result;
}

public function expand(string $name, array $variables = array())
{
$result = false;

if(isset($this->__snippets[$name]))
{
$snippet = $this->__snippets[$name];

//Use the php template engine to evaluate
$str = "<?php \n echo <<<SNIPPET\n$snippet\nSNIPPET;\n";

$result = $this->getObject('template.engine.factory')
->createEngine('php')
->loadString($str)
->render($variables);

//Find single whitespace before " or before > in html tags and remove it
preg_match_all('#<\s*\w.*?>#', $result, $tags);

foreach($tags as $tag) {
$result = str_replace($tag, str_replace(array(' >', ' "'), array('>', '"'), $tag), $result);
}
}
else throw new RuntimeException('Snippet: '.$name.' does not exist');

return $result;
}
}