View.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Src;
  3. use Exception;
  4. class View
  5. {
  6. private string $view = '';
  7. private array $data = [];
  8. private string $root = '';
  9. private string $layout = 'layouts/main.php';
  10. public function __construct(string $view = '', array $data = [])
  11. {
  12. $this->root = $this->getRoot();
  13. $this->view = $view;
  14. $this->data = $data;
  15. }
  16. private function getRoot():string
  17. {
  18. global $app;
  19. $root = $app->settings->getRootPath();
  20. $path = $app->settings->getViewsPath();
  21. return $_SERVER['DOCUMENT_ROOT'] . $root . $path;
  22. }
  23. private function getPathToMain(): string
  24. {
  25. return $this->root . '/' . $this->layout;
  26. }
  27. private function getPathToView(string $view = ''): string
  28. {
  29. $view = str_replace('.', '/', $view);
  30. return $this->getRoot() . "/$view.php";
  31. }
  32. public function render(string $view = '', array $data = []): string
  33. {
  34. $path = $this->getPathToView($view);
  35. if(file_exists($this->getPathToMain()) && file_exists($path)) {
  36. extract($data, EXTR_PREFIX_SAME, '');
  37. ob_start();
  38. require $path;
  39. $content = ob_get_clean();
  40. return require($this->getPathToMain());
  41. }
  42. throw new Exception('Render error');
  43. }
  44. public function __toString(): string
  45. {
  46. return $this->render($this->view, $this->data);
  47. }
  48. }