Passed
Push — 5.2 ( 7ec591...329a32 )
by
unknown
02:32
created

Http::runWithRequest()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 4
nop 1
dl 0
loc 19
rs 9.9666
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
1 ignored issue
show
Coding Style introduced by
You must use "/**" style comments for a file comment
Loading history...
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;
14
15
use think\exception\HttpException;
16
use Throwable;
17
18
/**
19
 * Web应用管理类
20
 */
5 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @package tag in class comment
Loading history...
Coding Style introduced by
Missing @author tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
21
class Http
22
{
23
24
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
25
     * @var App
26
     */
27
    protected $app;
28
29
    /**
30
     * 应用路径
31
     * @var string
32
     */
33
    protected $path;
34
35
    /**
36
     * 是否多应用模式
37
     * @var bool
38
     */
39
    protected $multi = false;
40
41
    /**
42
     * 是否域名绑定应用
43
     * @var bool
44
     */
45
    protected $bindDomain = false;
46
47
    /**
48
     * 应用名称
49
     * @var string
50
     */
51
    protected $name;
52
53
    public function __construct(App $app)
0 ignored issues
show
Coding Style introduced by
Missing function doc comment
Loading history...
54
    {
55
        $this->app   = $app;
56
        $this->multi = is_dir($this->app->getBasePath() . 'controller') ? false : true;
57
    }
58
59
    /**
60
     * 是否域名绑定应用
61
     * @access public
62
     * @return bool
63
     */
64
    public function isBindDomain(): bool
65
    {
66
        return $this->bindDomain;
67
    }
68
69
    /**
70
     * 设置应用模式
71
     * @access public
72
     * @param bool $multi
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 1
Loading history...
73
     * @return $this
74
     */
75
    public function multi(bool $multi)
76
    {
77
        $this->multi = $multi;
78
        return $this;
79
    }
80
81
    /**
82
     * 是否为多应用模式
83
     * @access public
84
     * @return bool
85
     */
86
    public function isMulti(): bool
87
    {
88
        return $this->multi;
89
    }
90
91
    /**
92
     * 设置应用名称
93
     * @access public
94
     * @param string $name 应用名称
1 ignored issue
show
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 1
Loading history...
95
     * @return $this
96
     */
97
    public function name(string $name)
98
    {
99
        $this->name = $name;
100
        return $this;
101
    }
102
103
    /**
104
     * 获取应用名称
105
     * @access public
106
     * @return string
107
     */
108
    public function getName(): string
109
    {
110
        return $this->name ?: '';
111
    }
112
113
    /**
114
     * 设置应用目录
115
     * @access public
116
     * @param string $path 应用目录
1 ignored issue
show
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 1
Loading history...
117
     * @return $this
118
     */
119
    public function path(string $path)
120
    {
121
        $this->path = $path;
122
        return $this;
123
    }
124
125
    /**
126
     * 执行应用程序
127
     * @access public
128
     * @param Request|null $request
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 1
Loading history...
129
     * @return Response
130
     */
131
    public function run(Request $request = null): Response
132
    {
133
        //自动创建request对象
134
        $request = $request ?? $this->app->make('request', [], true);
135
        $this->app->instance('request', $request);
136
137
        try {
138
            $response = $this->runWithRequest($request);
139
        } catch (Throwable $e) {
140
            $this->reportException($e);
141
142
            $response = $this->renderException($request, $e);
143
        }
144
145
        return $response;
146
    }
147
148
    /**
149
     * 初始化
150
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
151
    protected function initialize()
152
    {
153
        if (!$this->app->initialized()) {
154
            $this->app->initialize();
155
        }
156
    }
157
158
    /**
159
     * 执行应用程序
160
     * @param Request $request
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 1
Loading history...
161
     * @return mixed
162
     */
163
    protected function runWithRequest(Request $request)
164
    {
165
        $this->initialize();
166
167
        if ($this->multi) {
168
            $this->parseMultiApp();
169
        }
170
171
        // 设置开启事件机制
172
        $this->app->event->withEvent($this->app->config->get('app.with_event', true));
0 ignored issues
show
Bug introduced by
It seems like $this->app->config->get('app.with_event', true) can also be of type array and array; however, parameter $event of think\Event::withEvent() does only seem to accept boolean, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

172
        $this->app->event->withEvent(/** @scrutinizer ignore-type */ $this->app->config->get('app.with_event', true));
Loading history...
173
174
        // 监听AppInit
175
        $this->app->event->trigger('HttpRun');
176
177
        $withRoute = $this->app->config->get('app.with_route', true) ? function () {
178
            $this->loadRoutes();
179
        } : null;
180
181
        return $this->app->route->dispatch($request, $withRoute);
182
    }
183
184
    /**
185
     * 加载路由
186
     * @access protected
187
     * @return void
188
     */
189
    protected function loadRoutes(): void
190
    {
191
        // 加载路由定义
192
        if (is_dir($this->getRoutePath())) {
193
            $files = glob($this->getRoutePath() . '*.php');
194
            foreach ($files as $file) {
195
                include $file;
196
            }
197
        }
198
199
        if ($this->app->route->config('route_annotation')) {
200
            // 自动生成注解路由定义
201
            if ($this->app->isDebug()) {
202
                $this->app->build->buildRoute();
203
            }
204
205
            $filename = $this->app->getRuntimePath() . 'build_route.php';
206
207
            if (is_file($filename)) {
208
                include $filename;
209
            }
210
        }
211
    }
212
213
    /**
214
     * 获取路由目录
215
     * @access protected
216
     * @return string
217
     */
218
    protected function getRoutePath(): string
219
    {
220
        return $this->app->getRootPath() . 'route' . DIRECTORY_SEPARATOR . ($this->isMulti() ? $this->getName() . DIRECTORY_SEPARATOR : '');
221
    }
222
223
    /**
224
     * Report the exception to the exception handler.
225
     *
226
     * @param Throwable $e
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 1
Loading history...
227
     * @return void
228
     */
229
    protected function reportException(Throwable $e)
230
    {
231
        $this->app['error_handle']->report($e);
232
    }
233
234
    /**
235
     * Render the exception to a response.
236
     *
237
     * @param Request    $request
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 1
Loading history...
238
     * @param Throwable $e
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 1
Loading history...
239
     * @return Response
240
     */
241
    protected function renderException($request, Throwable $e)
242
    {
243
        return $this->app['error_handle']->render($request, $e);
244
    }
245
246
    /**
247
     * 获取当前运行入口名称
248
     * @access protected
249
     * @return string
250
     */
251
    protected function getScriptName(): string
252
    {
253
        if (isset($_SERVER['SCRIPT_FILENAME'])) {
254
            $file = $_SERVER['SCRIPT_FILENAME'];
255
        } elseif (isset($_SERVER['argv'][0])) {
256
            $file = realpath($_SERVER['argv'][0]);
257
        }
258
259
        return isset($file) ? pathinfo($file, PATHINFO_FILENAME) : '';
260
    }
261
262
    /**
263
     * 解析多应用
264
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
265
    protected function parseMultiApp(): void
266
    {
267
        if ($this->app->config->get('app.auto_multi_app', false)) {
268
            // 自动多应用识别
269
            $this->bindDomain = false;
270
271
            $bind = $this->app->config->get('app.domain_bind', []);
272
273
            if (!empty($bind)) {
274
                // 获取当前子域名
275
                $subDomain = $this->app->request->subDomain();
276
                $domain    = $this->app->request->host();
277
278
                if (isset($bind[$domain])) {
279
                    $appName          = $bind[$domain];
280
                    $this->bindDomain = true;
281
                } elseif (isset($bind[$subDomain])) {
282
                    $appName          = $bind[$subDomain];
283
                    $this->bindDomain = true;
284
                }
285
            }
286
287
            if (!$this->bindDomain) {
288
                $map  = $this->app->config->get('app.app_map', []);
289
                $path = $this->app->request->pathinfo();
290
                $name = current(explode('/', $path));
291
292
                if (isset($map[$name])) {
293
                    if ($map[$name] instanceof \Closure) {
294
                        call_user_func_array($map[$name], [$this->app]);
295
                    } else {
296
                        $appName = $map[$name];
297
                    }
298
                } elseif ($name && false !== array_search($name, $map)) {
299
                    throw new HttpException(404, 'app not exists:' . $name);
300
                } else {
301
                    $appName = $name;
302
                }
303
304
                if ($name) {
305
                    $this->app->request->setRoot($name);
306
                    $this->app->request->setPathinfo(strpos($path, '/') ? ltrim(strstr($path, '/'), '/') : '');
307
                }
308
            }
309
        } else {
310
            $appName = $this->name ?: $this->getScriptName();
311
        }
312
313
        $this->loadApp($appName ?: $this->app->config->get('app.default_app', 'index'));
0 ignored issues
show
Bug introduced by
It seems like $appName ?: $this->app->....default_app', 'index') can also be of type array and array; however, parameter $appName of think\Http::loadApp() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

313
        $this->loadApp(/** @scrutinizer ignore-type */ $appName ?: $this->app->config->get('app.default_app', 'index'));
Loading history...
Comprehensibility Best Practice introduced by
The variable $appName does not seem to be defined for all execution paths leading up to this point.
Loading history...
314
    }
315
316
    protected function loadApp(string $appName): void
0 ignored issues
show
Coding Style introduced by
Missing function doc comment
Loading history...
317
    {
318
        $this->name = $appName;
319
        $this->app->request->setApp($appName);
320
        $this->app->setAppPath($this->path ?: $this->app->getBasePath() . $appName . DIRECTORY_SEPARATOR);
321
        $this->app->setRuntimePath($this->app->getRootPath() . 'runtime' . DIRECTORY_SEPARATOR . $appName . DIRECTORY_SEPARATOR);
322
323
        //加载app文件
324
        if (is_file($this->app->getRuntimePath() . 'init.php')) {
325
            //直接加载缓存
326
            include $this->app->getRuntimePath() . 'init.php';
327
        } else {
328
            $appPath = $this->app->getAppPath();
329
330
            if (is_file($appPath . 'common.php')) {
331
                include_once $appPath . 'common.php';
332
            }
333
334
            $configPath = $this->app->getConfigPath();
335
336
            $files = [];
337
338
            if (is_dir($appPath . 'config')) {
339
                $files = array_merge($files, glob($appPath . 'config' . DIRECTORY_SEPARATOR . '*' . $this->app->getConfigExt()));
340
            } elseif (is_dir($configPath . $appName)) {
341
                $files = array_merge($files, glob($configPath . $appName . DIRECTORY_SEPARATOR . '*' . $this->app->getConfigExt()));
342
            }
343
344
            foreach ($files as $file) {
345
                $this->app->config->load($file, pathinfo($file, PATHINFO_FILENAME));
346
            }
347
348
            if (is_file($appPath . 'event.php')) {
349
                $this->app->loadEvent(include $appPath . 'event.php');
350
            }
351
352
            if (is_file($appPath . 'middleware.php')) {
353
                $this->app->middleware->import(include $appPath . 'middleware.php');
354
            }
355
356
            if (is_file($appPath . 'provider.php')) {
357
                $this->app->bind(include $appPath . 'provider.php');
358
            }
359
        }
360
361
        $this->app->setNamespace($this->app->config->get('app.app_namespace') ?: $this->app->getRootNamespace() . '\\' . $appName);
0 ignored issues
show
Bug introduced by
It seems like $this->app->config->get(...pace() . '\' . $appName can also be of type array; however, parameter $namespace of think\App::setNamespace() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

361
        $this->app->setNamespace(/** @scrutinizer ignore-type */ $this->app->config->get('app.app_namespace') ?: $this->app->getRootNamespace() . '\\' . $appName);
Loading history...
362
    }
363
}
364