Completed
Push — 6.0 ( 388f26...ecd628 )
by liu
05:39
created

Php::getConfig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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