diff options
Diffstat (limited to 'src/Renderer')
-rw-r--r-- | src/Renderer/EngineInterface.php | 21 | ||||
-rw-r--r-- | src/Renderer/HtmlEngine.php | 34 | ||||
-rw-r--r-- | src/Renderer/Renderer.php | 62 |
3 files changed, 117 insertions, 0 deletions
diff --git a/src/Renderer/EngineInterface.php b/src/Renderer/EngineInterface.php new file mode 100644 index 00000000..ca468db5 --- /dev/null +++ b/src/Renderer/EngineInterface.php @@ -0,0 +1,21 @@ +<?php + +namespace Engelsystem\Renderer; + +interface EngineInterface +{ + /** + * Render a template + * + * @param string $path + * @param mixed[] $data + * @return string + */ + public function get($path, $data = []); + + /** + * @param string $path + * @return bool + */ + public function canRender($path); +} diff --git a/src/Renderer/HtmlEngine.php b/src/Renderer/HtmlEngine.php new file mode 100644 index 00000000..4a48e1f0 --- /dev/null +++ b/src/Renderer/HtmlEngine.php @@ -0,0 +1,34 @@ +<?php + +namespace Engelsystem\Renderer; + +class HtmlEngine implements EngineInterface +{ + /** + * Render a template + * + * @param string $path + * @param mixed[] $data + * @return string + */ + public function get($path, $data = []) + { + $template = file_get_contents($path); + if (is_array($data)) { + foreach ($data as $name => $content) { + $template = str_replace('%' . $name . '%', $content, $template); + } + } + + return $template; + } + + /** + * @param string $path + * @return bool + */ + public function canRender($path) + { + return strpos($path, '.html') && file_exists($path); + } +} diff --git a/src/Renderer/Renderer.php b/src/Renderer/Renderer.php new file mode 100644 index 00000000..bf3d5609 --- /dev/null +++ b/src/Renderer/Renderer.php @@ -0,0 +1,62 @@ +<?php + +namespace Engelsystem\Renderer; + +use ErrorException; + +class Renderer +{ + /** @var self */ + protected static $instance; + + /** @var EngineInterface[] */ + protected $renderer = []; + + /** + * Render a template + * + * @param string $template + * @param mixed[] $data + * @return string + */ + public function render($template, $data = []) + { + foreach ($this->renderer as $renderer) { + if (!$renderer->canRender($template)) { + continue; + } + + return $renderer->get($template, $data); + } + + engelsystem_error('Unable to find a renderer for template file «' . $template . '».'); + return ''; + } + + /** + * Add a new renderer engine + * + * @param EngineInterface $renderer + */ + public function addRenderer(EngineInterface $renderer) + { + $this->renderer[] = $renderer; + } + + /** + * @return self + * @throws ErrorException + */ + public static function getInstance() + { + return self::$instance; + } + + /** + * @param self $instance + */ + public static function setInstance($instance) + { + self::$instance = $instance; + } +} |