renderer.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace la_restaurant_theme;
  3. class renderer {
  4. private string $start;
  5. private string $stop;
  6. private array $attributes;
  7. public static function from(string $template): object {
  8. return new renderer($template);
  9. }
  10. public function __construct(private string $content) {
  11. $this->start = '<<!';
  12. $this->stop = '!>>';
  13. $this->attributes = array();
  14. }
  15. public function set(string $name, string $content): object {
  16. $name = trim($name);
  17. $this->attributes[$name] = $content;
  18. return $this;
  19. }
  20. public function render(): string {
  21. $parts = explode($this->start, $this->content);
  22. $first = array_shift($parts);
  23. $results = array();
  24. array_push($results, $first);
  25. foreach ($parts as $count) {
  26. array_push($results, $this->process_single($count));
  27. }
  28. return join("", $results);
  29. }
  30. public function get_attribute(
  31. string $name,
  32. ?string $blank = null
  33. ): ?string {
  34. $name = trim($name);
  35. if (array_key_exists($name, $this->attributes)) {
  36. return $this->attributes[$name];
  37. }
  38. return $blank;
  39. }
  40. private function process_single(string $count): string {
  41. $parts = explode($this->stop, $count);
  42. if (count($parts) === 1) {
  43. return $this->start.$count;
  44. }
  45. $name = array_shift($parts);
  46. $name = trim($name);
  47. $rest = join($this->stop, $parts);
  48. $replace = $this->get_attribute($name, '');
  49. return $replace.$rest;
  50. }
  51. public function __get(string $name): mixed {
  52. switch ($name) {
  53. case 'start':
  54. return $this->start;
  55. case 'stop':
  56. return $this->stop;
  57. }
  58. }
  59. }