Bicycle/System/Classes/View.php
Egor Isaev b516ca07dc Initial commit: Bicycle PHP MVC micro-framework
Core MVC, HTTP client, Session, Cookie, Config, HTTPException — 111 PHPUnit tests.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-04 10:04:19 +03:00

90 lines
2.1 KiB
PHP

<?php
/**
* @package Bicycle
* @author Egor Isaev
* @description View.php
* @copyright (c) 03/06/2026
*/
namespace System\Classes;
use Throwable;
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
*/
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;
}
/**
* @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()}", 0, $e
);
}
}
}