Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php declare(strict_types = 1);
- namespace Xxxxxx\Support\Unit\Traits;
- use Jenssegers\Blade\Blade;
- use Exception;
- use ReflectionObject;
- trait TemplateTrait
- {
- protected ?Blade $template = null;
- protected ?string $dir = null;
- protected ?string $templateDir = null;
- protected ?string $templateCacheDir = null;
- protected string $viewName = '';
- private static $instance = null;
- /**
- * getDir
- *
- * @return string
- */
- public function getDir(): string
- {
- return $this->dir;
- }
- /**
- * getTemplateDir
- *
- * @return string
- */
- public function getTemplateDir(): string
- {
- return $this->templateDir;
- }
- /**
- * setViewName
- *
- * @return string
- */
- public function setViewName(string $viewName): void
- {
- $this->viewName = $viewName;
- }
- /**
- * getViewName
- *
- * @return string
- */
- public function getViewName(): string
- {
- return $this->viewName;
- }
- /**
- * instance
- *
- * @return static::class
- */
- public static function instance()
- {
- if (static::$instance === null) {
- $instance = new static();
- static::$instance = $instance;
- }
- return static::$instance;
- }
- /**
- * view
- *
- * @param mixed $viewName
- * @return void
- */
- public function view(string $viewName)
- {
- $this->setViewName($viewName);
- if (!file_exists($this->getTemplateDir() . '/'. $this->getViewName())) throw new Exception('Template '.$viewName.' does not exists.');
- return $this;
- }
- /**
- * getInstanceObjectFilePath
- *
- * @return string
- */
- public function getInstanceObjectFilePath(): string
- {
- return plugin_dir_path((new ReflectionObject($this))->getFilename());
- }
- /**
- * template
- *
- * @return void
- */
- public function template()
- {
- $this->dir = $this->getInstanceObjectFilePath();
- $this->templateDir = $this->dir . 'Views';
- $this->templateCacheDir = $this->dir . 'Views/Cache';
- if (!is_dir($this->templateDir)) throw new Exception('Views directory does not exists at: ' . $this->dir);
- if (!is_dir($this->templateCacheDir)) throw new Exception('Views/Cache directory does not exists at: ' . $this->dir);
- $this->template = new Blade(
- $this->templateDir,
- $this->templateCacheDir,
- );
- if ($this->template === null) throw new Exception('Template was not initialized');
- return $this;
- }
- /**
- * render
- *
- * @param mixed $arguments
- * @return void
- */
- public function render(array $arguments): void
- {
- print $this->template->render(
- $this->getViewName(),
- $arguments,
- );
- return;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement