1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <?php
- declare(strict_types=1);
- namespace App\View\Engine;
- use Hyperf\View\Engine\EngineInterface;
- use Smarty;
- use RuntimeException;
- class SmartyEngine implements EngineInterface
- {
- protected Smarty $smarty;
- public function __construct(array $options = [])
- {
- $this->smarty = new Smarty();
- // 设置模板目录
- $this->smarty->setTemplateDir($options['template_dir'] ?? BASE_PATH . '/storage/view/');
- $this->smarty->setCompileDir($options['compile_dir'] ?? BASE_PATH . '/runtime/smarty/compile/');
- $this->smarty->setCacheDir($options['cache_dir'] ?? BASE_PATH . '/runtime/smarty/cache/');
- // 设置定界符
- $this->smarty->setLeftDelimiter($options['left_delimiter'] ?? '{{');
- $this->smarty->setRightDelimiter($options['right_delimiter'] ?? '}}');
- // 确保目录存在
- $this->ensureDirectoryExists($this->smarty->getCompileDir());
- $this->ensureDirectoryExists($this->smarty->getCacheDir());
- }
- protected function ensureDirectoryExists(string $path): void
- {
- if (!is_dir($path)) {
- mkdir($path, 0755, true);
- }
- }
- public function render(string $template, array $data, array $config): string
- {
- // 标准化模板路径
- $template = $this->normalizeTemplatePath($template);
- // 获取完整模板路径
- $templatePath = $this->smarty->getTemplateDir()[0] . $template;
- // 检查模板文件是否存在
- if (!file_exists($templatePath)) {
- throw new RuntimeException("Template file not found: {$templatePath}");
- }
- // 分配变量
- foreach ($data as $key => $value) {
- $this->smarty->assign($key, $value);
- }
- try {
- return $this->smarty->fetch($templatePath);
- } catch (\SmartyException $e) {
- throw new RuntimeException("Smarty render failed: " . $e->getMessage());
- }
- }
- protected function normalizeTemplatePath(string $path): string
- {
- // 移除可能的绝对路径前缀
- $path = str_replace(BASE_PATH, '', $path);
- // 移除开头的斜杠
- $path = ltrim($path, '/');
- // 确保使用正确的扩展名
- if (!str_ends_with($path, '.tpl')) {
- $path .= '.tpl';
- }
- return $path;
- }
- }
|