template.class.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. <?php
  2. namespace Juju\Data;
  3. require_once(realpath(dirname(__DIR__).'/events.trait.php'));
  4. require_once('earray.class.php');
  5. use Juju\{Events, Data\EArray};
  6. use \Exception;
  7. class Template {
  8. use Events;
  9. private static $templates = [];
  10. private $template;
  11. private $name;
  12. public function __construct(string $name, callable $template){
  13. if(isset(static::$templates[$name])){
  14. throw new Exception("Template {$name} already exists");
  15. }
  16. $this->template = $template;
  17. $this->name = $name;
  18. static::$templates[$name] = $this;
  19. }
  20. public function run(array $data) : string{
  21. $data = EArray::from($data);
  22. if($this->fire('before', $data) === false){
  23. throw new Exception("Render on template {$this->name} cancelled. Before.");
  24. }
  25. $output = \Closure::FromCallable($this->template)->call($data);
  26. if($this->fire('after', $output) === false){
  27. throw new Exception("Render on template {$this->name} cancelled. After");
  28. }
  29. return (string)$output;
  30. }
  31. public static function from(string $name, array $data = []) : string{
  32. $template = static::$templates[$name] ?? null;
  33. if(is_null($template)){
  34. throw new Exception("Template {$name} does not exist");
  35. }
  36. return $template->run($data);
  37. }
  38. }
  39. ?>