Passed
Push — 6.0 ( f409e2...e26961 )
by liu
02:35
created

Http::end()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 10
rs 10
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
        // 监听HttpRun
175
        $this->app->event->trigger('HttpRun');
176
177
        $this->app->request->withCookie($this->app->cookie->get());
178
        $this->app->session->setName($this->app->config->get('session.name', 'PHPSESSID'));
0 ignored issues
show
Bug introduced by
It seems like $this->app->config->get(...ion.name', 'PHPSESSID') can also be of type array and array; however, parameter $name of think\Session::setName() 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

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

319
        $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...
320
    }
321
322
    /**
323
     * 加载应用文件
324
     * @param string $appName 应用名
1 ignored issue
show
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 1
Loading history...
325
     * @return void
326
     */
327
    protected function loadApp(string $appName): void
328
    {
329
        $this->name = $appName;
330
        $this->app->request->setApp($appName);
331
        $this->app->setAppPath($this->path ?: $this->app->getBasePath() . $appName . DIRECTORY_SEPARATOR);
332
        $this->app->setRuntimePath($this->app->getRootPath() . 'runtime' . DIRECTORY_SEPARATOR . $appName . DIRECTORY_SEPARATOR);
333
334
        //加载app文件
335
        if (is_file($this->app->getRuntimePath() . 'init.php')) {
336
            //直接加载缓存
337
            include $this->app->getRuntimePath() . 'init.php';
338
        } else {
339
            $appPath = $this->app->getAppPath();
340
341
            if (is_file($appPath . 'common.php')) {
342
                include_once $appPath . 'common.php';
343
            }
344
345
            $configPath = $this->app->getConfigPath();
346
347
            $files = [];
348
349
            if (is_dir($appPath . 'config')) {
350
                $files = array_merge($files, glob($appPath . 'config' . DIRECTORY_SEPARATOR . '*' . $this->app->getConfigExt()));
0 ignored issues
show
Bug introduced by
It seems like glob($appPath . 'config'...s->app->getConfigExt()) can also be of type false; however, parameter $array2 of array_merge() does only seem to accept array|null, 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

350
                $files = array_merge($files, /** @scrutinizer ignore-type */ glob($appPath . 'config' . DIRECTORY_SEPARATOR . '*' . $this->app->getConfigExt()));
Loading history...
351
            } elseif (is_dir($configPath . $appName)) {
352
                $files = array_merge($files, glob($configPath . $appName . DIRECTORY_SEPARATOR . '*' . $this->app->getConfigExt()));
353
            }
354
355
            foreach ($files as $file) {
356
                $this->app->config->load($file, pathinfo($file, PATHINFO_FILENAME));
357
            }
358
359
            if (is_file($appPath . 'event.php')) {
360
                $this->app->loadEvent(include $appPath . 'event.php');
361
            }
362
363
            if (is_file($appPath . 'middleware.php')) {
364
                $this->app->middleware->import(include $appPath . 'middleware.php');
365
            }
366
367
            if (is_file($appPath . 'provider.php')) {
368
                $this->app->bind(include $appPath . 'provider.php');
369
            }
370
        }
371
372
        $this->app->setNamespace($this->app->config->get('app.app_namespace') ?: 'app\\' . $appName);
0 ignored issues
show
Bug introduced by
It seems like $this->app->config->get(...') ?: 'app\' . $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

372
        $this->app->setNamespace(/** @scrutinizer ignore-type */ $this->app->config->get('app.app_namespace') ?: 'app\\' . $appName);
Loading history...
373
    }
374
375
    /**
376
     * HttpEnd
377
     * @return void
378
     */
379
    public function end(): void
380
    {
381
        $this->app->event->trigger('HttpEnd');
382
383
        // 写入日志
384
        $this->app->log->save();
385
        // 写入Cookie
386
        $this->app->cookie->save();
387
        // 写入Session
388
        $this->app->session->save();
389
    }
390
}
391