chengkun
2025-09-19 d48eff069585e2be1bd02b1299e1fe7581cb6dad
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2025 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
 
namespace think\view\driver;
 
use RuntimeException;
use think\App;
use think\contract\TemplateHandlerInterface;
use think\helper\Str;
 
/**
 * PHP原生模板驱动
 */
class Php implements TemplateHandlerInterface
{
    protected $template;
    protected $content;
    protected $app;
 
    // 模板引擎参数
    protected $config = [
        // 默认模板渲染规则 1 解析为小写+下划线 2 全部转换小写 3 保持操作方法
        'auto_rule'     => 1,
        // 视图目录名
        'view_dir_name' => 'view',
        // 应用模板路径
        'view_path'     => '',
        // 模板文件后缀
        'view_suffix'   => 'php',
        // 模板文件名分隔符
        'view_depr'     => DIRECTORY_SEPARATOR,
    ];
 
    public function __construct(App $app, array $config = [])
    {
        $this->app    = $app;
        $this->config = array_merge($this->config, (array) $config);
    }
 
    /**
     * 检测是否存在模板文件
     * @param string $template 模板文件或者模板规则
     * @return bool
     */
    public function exists(string $template): bool
    {
        $template = $this->getTemplateFile($template);
 
        return is_file($template);
    }
 
    protected function getTemplateFile(string $template): string
    {
        if ('' == pathinfo($template, PATHINFO_EXTENSION)) {
            // 获取模板文件名
            $template = $this->parseTemplate($template);
        } elseif (!is_file($template)) {
            $path     = $this->config['view_path'] ?: $this->getViewPath($this->app->http->getName());
            $template = $path . $template;
        }
 
        return $template;
    }
    
    /**
     * 渲染模板文件
     * @param string $template 模板文件
     * @param array  $data     模板变量
     * @return void
     */
    public function fetch(string $template, array $data = []): void
    {
        $template = $this->getTemplateFile($template);
 
        // 模板不存在 抛出异常
        if (!is_file($template)) {
            throw new RuntimeException('template not exists:' . $template);
        }
 
        $this->template = $template;
 
        extract($data, EXTR_OVERWRITE);
 
        include $this->template;
    }
 
    /**
     * 渲染模板内容
     * @param string $content 模板内容
     * @param array  $data    模板变量
     * @return void
     */
    public function display(string $content, array $data = []): void
    {
        $this->content = $content;
 
        extract($data, EXTR_OVERWRITE);
        eval('?>' . $this->content);
    }
 
    protected function getViewPath(string $app): string
    {
        $view  = $this->config['view_dir_name'] . DIRECTORY_SEPARATOR;
        $app   = $app ? str_replace('.', DIRECTORY_SEPARATOR, $app) . DIRECTORY_SEPARATOR : '';
        $paths = [
            $this->app->getBasePath() . $app . $view,
            $this->app->getBasePath() . $view . $app,
            $this->app->getRootPath() . $view . $app
        ];
 
        foreach ($paths as $path) {
            if (is_dir($path)) {
                return $path;
            }
        }
 
        return '';
    }
 
    /**
     * 自动定位模板文件
     * @param string $template 模板文件规则
     * @return string
     */
    private function parseTemplate(string $template): string
    {
        $request = $this->app->request;
 
        // 获取视图根目录
        if (str_contains($template, '@')) {
            // 跨应用调用
            [$app, $template] = explode('@', $template);
        } elseif ($this->app->http->getName()) {
            $app = $this->app->http->getName();
        } elseif ($request->layer()) {
            $app        = $request->layer();
            $controller = $request->controller(false, true);
        }
 
        if ($this->config['view_path']) {
            $path = $this->config['view_path'];
        } else {
            $path = $this->getViewPath($app ?? $this->app->http->getName());
        }
 
        $depr = $this->config['view_depr'];
 
        if (!str_starts_with($template, '/')) {
            $template   = str_replace(['/', ':'], $depr, $template);
            $controller = $controller ?? $request->controller();
            if (str_contains($controller, '.')) {
                $pos        = strrpos($controller, '.');
                $controller = substr($controller, 0, $pos) . '.' . Str::snake(substr($controller, $pos + 1));
            } else {
                $controller = Str::snake($controller);
            }
 
            if ($controller) {
                if ('' == $template) {
                    // 如果模板文件名为空 按照默认规则定位
                    if (2 == $this->config['auto_rule']) {
                        $template = $request->action(true);
                    } elseif (3 == $this->config['auto_rule']) {
                        $template = $request->action();
                    } else {
                        $template = Str::snake($request->action());
                    }
 
                    $template = str_replace('.', DIRECTORY_SEPARATOR, $controller) . $depr . $template;
                } elseif (!str_contains($template, $depr)) {
                    $template = str_replace('.', DIRECTORY_SEPARATOR, $controller) . $depr . $template;
                }
            }
        } else {
            $template = str_replace(['/', ':'], $depr, substr($template, 1));
        }
 
        return $path . ltrim($template, '/') . '.' . ltrim($this->config['view_suffix'], '.');
    }
 
    /**
     * 配置模板引擎
     * @param array $config 参数
     * @return void
     */
    public function config(array $config): void
    {
        $this->config = array_merge($this->config, $config);
    }
 
    /**
     * 获取模板引擎配置
     * @param string $name 参数名
     * @return mixed
     */
    public function getConfig(string $name)
    {
        return $this->config[$name] ?? null;
    }
}