Completed
Push — 6.0 ( 7c7d4e...388f26 )
by liu
06:20
created

Php::assign()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 3
cp 0
crap 2
rs 10
c 1
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
namespace think\view\driver;
14
15
use think\App;
16
use think\contract\TemplateHandlerInterface;
17
use think\helper\Str;
18
use think\template\exception\TemplateNotFoundException;
0 ignored issues
show
Bug introduced by
The type think\template\exception\TemplateNotFoundException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
19
20
/**
21
 * PHP原生模板驱动
22
 */
23
class Php implements TemplateHandlerInterface
24
{
25
    protected $template;
26
    protected $content;
27
    protected $app;
28
    protected $vars = [];
29
30
    // 模板引擎参数
31
    protected $config = [
32
        // 默认模板渲染规则 1 解析为小写+下划线 2 全部转换小写 3 保持操作方法
33
        'auto_rule'   => 1,
34
        // 视图根目录
35
        'view_base'   => '',
36
        // 应用模板起始路径
37
        'view_path'   => '',
38
        // 模板文件后缀
39
        'view_suffix' => 'php',
40
        // 模板文件名分隔符
41
        'view_depr'   => DIRECTORY_SEPARATOR,
42
    ];
43
44
    public function __construct(App $app, array $config = [])
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
45
    {
46
        $this->app    = $app;
47
        $this->config = array_merge($this->config, (array) $config);
48
    }
49
50
    /**
51
     * 检测是否存在模板文件
52
     * @access public
53
     * @param  string $template 模板文件或者模板规则
54
     * @return bool
55
     */
56
    public function exists(string $template): bool
57
    {
58
        if ('' == pathinfo($template, PATHINFO_EXTENSION)) {
59
            // 获取模板文件名
60
            $template = $this->parseTemplate($template);
61
        }
62
63
        return is_file($template);
64
    }
65
66
    /**
67
     * 模板变量赋值
68
     * @access public
69
     * @param  array $vars
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
70
     * @return $this
71
     */
72
    public function assign(array $vars = [])
73
    {
74
        $this->vars = array_merge($this->vars, $vars);
75
        return $this;
76
    }
77
78
    /**
79
     * 渲染模板文件
80
     * @access public
81
     * @param  string $template 模板文件
82
     * @param  array  $data 模板变量
0 ignored issues
show
Coding Style introduced by
Expected 5 spaces after parameter name; 1 found
Loading history...
83
     * @return void
84
     */
85
    public function fetch(string $template, array $data = []): void
86
    {
87
        if ('' == pathinfo($template, PATHINFO_EXTENSION)) {
88
            // 获取模板文件名
89
            $template = $this->parseTemplate($template);
90
        }
91
92
        // 模板不存在 抛出异常
93
        if (!is_file($template)) {
94
            throw new TemplateNotFoundException('template not exists:' . $template, $template);
95
        }
96
97
        $this->template = $template;
98
99
        $data = array_merge($this->vars, $data);
100
101
        // 记录视图信息
102
        $this->app->log
103
            ->record('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]');
104
105
        extract($data, EXTR_OVERWRITE);
106
107
        include $this->template;
108
    }
109
110
    /**
111
     * 渲染模板内容
112
     * @access public
113
     * @param  string $content 模板内容
114
     * @param  array  $data 模板变量
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
115
     * @return void
116
     */
117
    public function display(string $content, array $data = []): void
118
    {
119
        $this->content = $content;
120
121
        $data = array_merge($this->vars, $data);
122
123
        extract($data, EXTR_OVERWRITE);
124
        eval('?>' . $this->content);
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
125
    }
126
127
    /**
128
     * 自动定位模板文件
129
     * @access private
130
     * @param  string $template 模板文件规则
131
     * @return string
132
     */
133
    private function parseTemplate(string $template): string
0 ignored issues
show
Coding Style introduced by
Private method name "Php::parseTemplate" must be prefixed with an underscore
Loading history...
134
    {
135
        if (empty($this->config['view_base'])) {
136
            $this->config['view_base'] = $this->app->getRootPath() . 'view' . DIRECTORY_SEPARATOR;
137
        }
138
139
        $request = $this->app->request;
140
141
        // 获取视图根目录
142
        if (strpos($template, '@')) {
143
            // 跨模块调用
144
            list($app, $template) = explode('@', $template);
145
        }
146
147
        if ($this->config['view_path'] && !isset($app)) {
148
            $path = $this->config['view_path'];
149
        } else {
150
            $app = isset($app) ? $app : $request->app();
151
            // 基础视图目录
152
            $path = $this->config['view_base'] . ($app ? $app . DIRECTORY_SEPARATOR : '');
153
        }
154
155
        $depr = $this->config['view_depr'];
156
157
        if (0 !== strpos($template, '/')) {
158
            $template   = str_replace(['/', ':'], $depr, $template);
159
            $controller = $request->controller();
160
            if (strpos($controller, '.')) {
161
                $pos        = strrpos($controller, '.');
162
                $controller = substr($controller, 0, $pos) . '.' . Str::snake(substr($controller, $pos + 1));
163
            } else {
164
                $controller = Str::snake($controller);
165
            }
166
167
            if ($controller) {
168
                if ('' == $template) {
169
                    // 如果模板文件名为空 按照默认规则定位
170
                    if (2 == $this->config['auto_rule']) {
171
                        $template = $request->action(true);
172
                    } elseif (3 == $this->config['auto_rule']) {
173
                        $template = $request->action();
174
                    } else {
175
                        $template = Str::snake($request->action());
176
                    }
177
178
                    $template = str_replace('.', DIRECTORY_SEPARATOR, $controller) . $depr . $template;
179
                } elseif (false === strpos($template, $depr)) {
180
                    $template = str_replace('.', DIRECTORY_SEPARATOR, $controller) . $depr . $template;
181
                }
182
            }
183
        } else {
184
            $template = str_replace(['/', ':'], $depr, substr($template, 1));
185
        }
186
187
        return $path . ltrim($template, '/') . '.' . ltrim($this->config['view_suffix'], '.');
188
    }
189
190
    /**
191
     * 配置模板引擎
192
     * @access private
193
     * @param  array $config 参数
194
     * @return void
195
     */
196
    public function config(array $config): void
197
    {
198
        $this->config = array_merge($this->config, $config);
199
    }
200
201
    /**
202
     * 获取模板引擎配置
203
     * @access public
204
     * @param  string $name 参数名
205
     * @return mixed
206
     */
207
    public function getConfig(string $name)
208
    {
209
        return $this->config[$name] ?? null;
210
    }
211
}
212