94 lines
1.4 KiB
PHP
94 lines
1.4 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Kiri\Router\Blade;
|
|
|
|
/**
|
|
* Blade 视图类
|
|
* 管理视图的渲染和数据传递
|
|
*/
|
|
class BladeView
|
|
{
|
|
/**
|
|
* 视图名称
|
|
*/
|
|
protected string $view;
|
|
|
|
/**
|
|
* 视图数据
|
|
*/
|
|
protected array $data;
|
|
|
|
/**
|
|
* Blade 编译器实例
|
|
*/
|
|
protected BladeCompiler $compiler;
|
|
|
|
/**
|
|
* @param string $view 视图名称
|
|
* @param array $data 视图数据
|
|
* @param BladeCompiler $compiler 编译器实例
|
|
*/
|
|
public function __construct(string $view, array $data, BladeCompiler $compiler)
|
|
{
|
|
$this->view = $view;
|
|
$this->data = $data;
|
|
$this->compiler = $compiler;
|
|
}
|
|
|
|
/**
|
|
* 渲染视图
|
|
*
|
|
* @return string
|
|
*/
|
|
public function render(): string
|
|
{
|
|
// 编译视图
|
|
$compiledPath = $this->compiler->compile($this->view);
|
|
|
|
// 提取数据
|
|
extract($this->data, EXTR_SKIP);
|
|
|
|
// 初始化栈和 section 数组
|
|
$__stacks = [];
|
|
$__sections = [];
|
|
|
|
// 开始输出缓冲
|
|
ob_start();
|
|
|
|
try {
|
|
// 包含编译后的 PHP 文件
|
|
require $compiledPath;
|
|
} catch (\Throwable $e) {
|
|
ob_end_clean();
|
|
|
|
\Kiri::getLogger()->json_log($throwable);
|
|
|
|
throw new \RuntimeException("视图渲染失败: {$this->view}", 0, $e);
|
|
}
|
|
|
|
return ob_get_clean();
|
|
}
|
|
|
|
/**
|
|
* 获取视图名称
|
|
*
|
|
* @return string
|
|
*/
|
|
public function getView(): string
|
|
{
|
|
return $this->view;
|
|
}
|
|
|
|
/**
|
|
* 获取视图数据
|
|
*
|
|
* @return array
|
|
*/
|
|
public function getData(): array
|
|
{
|
|
return $this->data;
|
|
}
|
|
}
|
|
|