12345678910111213141516171819202122232425262728293031323334353637383940 |
- <?php
- namespace Juju\Data;
- require_once(realpath(dirname(__DIR__).'/events.trait.php'));
- require_once('earray.class.php');
- use Juju\{Events, Data\EArray};
- use \Exception;
- class Template {
- use Events;
- private static $templates = [];
- private $template;
- private $name;
- public function __construct(string $name, callable $template){
- if(isset(static::$templates[$name])){
- throw new Exception("Template {$name} already exists");
- }
- $this->template = $template;
- $this->name = $name;
- static::$templates[$name] = $this;
- }
- public function run(array $data) : string{
- $data = EArray::from($data);
- if($this->fire('before', $data) === false){
- throw new Exception("Render on template {$this->name} cancelled. Before.");
- }
- $output = \Closure::FromCallable($this->template)->call($data);
- if($this->fire('after', $output) === false){
- throw new Exception("Render on template {$this->name} cancelled. After");
- }
- return (string)$output;
- }
- public static function from(string $name, array $data = []) : string{
- $template = static::$templates[$name] ?? null;
- if(is_null($template)){
- throw new Exception("Template {$name} does not exist");
- }
- return $template->run($data);
- }
- }
- ?>
|