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 92 93 94 95 96 97 98 99 100
<?php
namespace ICanBoogie\Render;
use ICanBoogie\ActiveRecord\Query;
class Renderer
{
private $original_template_resolver;
private $engines;
protected $template_resolver;
public function __construct(TemplateResolver $template_resolver, EngineCollection $engines)
{
$this->original_template_resolver = $template_resolver;
$this->engines = $engines;
}
public function render($target_or_options, array $additional_options=[])
{
$this->template_resolver = clone $this->original_template_resolver;
$options = $this->resolve_options($target_or_options, $additional_options);
if (isset($options['partial']))
{
$tried = [];
$template = TemplateName::from($options['partial'])->as_partial;
$template_pathname = $this->template_resolver->resolve($template, $this->engines->extensions, $tried);
if (!$template_pathname)
{
throw new TemplateNotFound("There is no partial matching <q>$template</q>.", $tried);
}
return $this->engines->render($template_pathname, null, $options['locals']);
}
$tried = [];
$template = $options['template'];
$template_pathname = $this->template_resolver->resolve($template, $this->engines->extensions, $tried);
if (!$template_pathname)
{
throw new TemplateNotFound("There is no template matching <q>$template</q>.", $tried);
}
return $this->engines->render($template_pathname, $options['content'], $options['locals']);
}
protected function resolve_options($target_or_options, array $additional_options=[])
{
$options = [];
if (is_object($target_or_options))
{
$additional_options['content'] = $target_or_options;
$additional_options['locals']['this'] = $target_or_options;
$additional_options['partial'] = $this->resolve_template($target_or_options);
if ($target_or_options instanceof Query)
{
$model_id = $target_or_options->model->id;
$module_path = \ICanBoogie\app()->modules[$model_id]->path;
$this->template_resolver->add_path($module_path . 'templates');
}
}
else if (is_array($target_or_options))
{
$options = $target_or_options;
}
return $additional_options + $options;
}
protected function resolve_template($content)
{
return TemplateName::from($content);
}
}