Bicycle/System/Classes/View.php
Egor Isaev e6e8844f2b dev
2026-06-23 14:17:26 +03:00

99 lines
3.0 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* @package Bicycle
* @author Egor Isaev
* @description View.php
* @copyright (c) 03/06/2026
*/
namespace System\Classes;
use Throwable;
/**
* Рендеринг .html-шаблонов через ob_start + extract + include.
*/
class View
{
/**
* @var string Полный путь к найденному файлу шаблона
*/
public string $_file;
/**
* @var array Данные, доступные внутри шаблона
*/
public array $_data = [];
/**
* @param string|null $file Имя файла шаблона без расширения
* @param string $dir Каталог шаблона относительно базовых путей
* @param array|null $data Данные для шаблона
* @throws MyException
*/
public function __construct(?string $file = null, string $dir = '', ?array $data = null)
{
if ($file !== null) {
$this->setFilename($file, $dir);
}
if ($data !== null) {
// Добавить значения к текущим данным
$this->_data = $data + $this->_data;
}
}
/**
* Устанавливает файл шаблона, проверяя его существование.
*
* @param string $file Имя файла шаблона без расширения
* @param string $dir Каталог шаблона (обязателен)
* @return View
* @throws MyException Если $dir пуст или файл не найден
*/
public function setFilename(string $file, string $dir = ''): View
{
if ($dir === '') {
throw new MyException("Параметр dir не передан в View::setFilename для файла '$file'");
}
if (($path = Core::findFile($dir, $file, 'html')) === false) {
throw new MyException("При запросе view файл $dir/$file не найден");
}
// Store the file path locally
$this->_file = $path;
return $this;
}
/**
* Выполняет шаблон и возвращает результат как строку.
*
* @return string Отрендеренный HTML
* @throws MyException Если файл не установлен или ошибка при рендеринге
*/
public function render(): string
{
if (empty($this->_file)) {
throw new MyException('Нужно установить файл для использования во view перед преобразованием');
}
ob_start();
extract($this->_data, EXTR_SKIP);
try {
include $this->_file;
return ob_get_clean();
} catch (Throwable $e) {
ob_end_clean();
throw new MyException(
"Ошибка при render файла: {$e->getFile()} на строке {$e->getLine()} - {$e->getMessage()}", null, 0, $e
);
}
}
}