TemplateEngine.php
1 year ago
TemplateEngineException.php
5 years ago
TemplateEngineInterface.php
1 year ago
TemplateEngine.php
87 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WPStaging\Framework\TemplateEngine; |
| 4 | |
| 5 | use DateTime; |
| 6 | use WPStaging\Core\WPStaging; |
| 7 | use WPStaging\Framework\Adapter\DateTimeAdapter; |
| 8 | use WPStaging\Framework\Assets\Assets; |
| 9 | |
| 10 | class TemplateEngine implements TemplateEngineInterface |
| 11 | { |
| 12 | /** |
| 13 | * Hook that is used to inject pro templates in UI. So they can be used by our JS |
| 14 | * @var string |
| 15 | */ |
| 16 | const HOOK_RENDER_PRO_TEMPLATES = 'wpstg.template.render_pro_templates'; |
| 17 | |
| 18 | /** @var string Absolute path to the views directory. */ |
| 19 | protected $views; |
| 20 | |
| 21 | /** @var Assets */ |
| 22 | private $assets; |
| 23 | |
| 24 | public function __construct() |
| 25 | { |
| 26 | $this->assets = WPStaging::make(Assets::class); |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * @param string $path |
| 31 | * @param array $params |
| 32 | * |
| 33 | * @return string |
| 34 | */ |
| 35 | public function render(string $path, array $params = []): string |
| 36 | { |
| 37 | if (!isset($this->views)) { |
| 38 | $this->views = WPSTG_VIEWS_DIR; |
| 39 | } |
| 40 | |
| 41 | $fullPath = WPSTG_VIEWS_DIR . $path; |
| 42 | if (!file_exists($fullPath)) { |
| 43 | throw new TemplateEngineException('Template not found: ' . $fullPath); |
| 44 | } |
| 45 | |
| 46 | extract($params, EXTR_SKIP); |
| 47 | ob_start(); |
| 48 | |
| 49 | /** @noinspection PhpIncludeInspection */ |
| 50 | require $fullPath; |
| 51 | $result = ob_get_clean(); |
| 52 | |
| 53 | return (string)$result; |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * @return Assets |
| 58 | */ |
| 59 | public function getAssets() |
| 60 | { |
| 61 | return $this->assets; |
| 62 | } |
| 63 | |
| 64 | /** |
| 65 | * @return string |
| 66 | * @noinspection PhpUnused |
| 67 | */ |
| 68 | protected function getDateTimeFormat(): string |
| 69 | { |
| 70 | return (new DateTimeAdapter())->getDateTimeFormat(); |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * @param DateTime|null $dateTime |
| 75 | * |
| 76 | * @return string |
| 77 | */ |
| 78 | protected function transformToWpFormat($dateTime = null): string |
| 79 | { |
| 80 | if (!$dateTime) { |
| 81 | return ''; |
| 82 | } |
| 83 | |
| 84 | return (new DateTimeAdapter())->transformToWpFormat($dateTime); |
| 85 | } |
| 86 | } |
| 87 |