Completed
Push — 6.0 ( 198279...8d8f1e )
by liu
02:32
created

Http::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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

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

326
        $this->loadApp(/** @scrutinizer ignore-type */ $appName ?: $this->app->config->get('app.default_app', 'index'));
Loading history...
327 5
    }
328
329
    /**
330
     * 加载应用文件
331
     * @param string $appName 应用名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
332
     * @return void
333
     */
334 5
    protected function loadApp(string $appName): void
335
    {
336 5
        $this->name = $appName;
337 5
        $this->app->request->setApp($appName);
338 5
        $this->app->setAppPath($this->path ?: $this->app->getBasePath() . $appName . DIRECTORY_SEPARATOR);
339 5
        $this->app->setRuntimePath($this->app->getRootPath() . 'runtime' . DIRECTORY_SEPARATOR . $appName . DIRECTORY_SEPARATOR);
340
341
        //加载app文件
342 5
        if (is_dir($this->app->getAppPath())) {
343 1
            if (is_file($this->app->getRuntimePath() . 'init.php')) {
344
                //直接加载缓存
345
                include $this->app->getRuntimePath() . 'init.php';
346
            } else {
347 1
                $appPath = $this->app->getAppPath();
348
349 1
                if (is_file($appPath . 'common.php')) {
350 1
                    include_once $appPath . 'common.php';
351
                }
352
353 1
                $configPath = $this->app->getConfigPath();
354
355 1
                $files = [];
356
357 1
                if (is_dir($configPath . $appName)) {
358 1
                    $files = array_merge($files, glob($configPath . $appName . DIRECTORY_SEPARATOR . '*' . $this->app->getConfigExt()));
0 ignored issues
show
Bug introduced by
It seems like glob($configPath . $appN...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

358
                    $files = array_merge($files, /** @scrutinizer ignore-type */ glob($configPath . $appName . DIRECTORY_SEPARATOR . '*' . $this->app->getConfigExt()));
Loading history...
359
                } elseif (is_dir($appPath . 'config')) {
360
                    $files = array_merge($files, glob($appPath . 'config' . DIRECTORY_SEPARATOR . '*' . $this->app->getConfigExt()));
361
                }
362
363 1
                foreach ($files as $file) {
364
                    $this->app->config->load($file, pathinfo($file, PATHINFO_FILENAME));
365
                }
366
367 1
                if (is_file($appPath . 'event.php')) {
368 1
                    $this->app->loadEvent(include $appPath . 'event.php');
369
                }
370
371 1
                if (is_file($appPath . 'middleware.php')) {
372 1
                    $this->app->middleware->import(include $appPath . 'middleware.php');
373
                }
374
375 1
                if (is_file($appPath . 'provider.php')) {
376 1
                    $this->app->bind(include $appPath . 'provider.php');
377
                }
378
            }
379
        }
380
381 5
        $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

381
        $this->app->setNamespace(/** @scrutinizer ignore-type */ $this->app->config->get('app.app_namespace') ?: 'app\\' . $appName);
Loading history...
382 5
    }
383
384
    /**
385
     * HttpEnd
386
     * @param Response $response
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
387
     * @return void
388
     */
389 1
    public function end(Response $response): void
390
    {
391 1
        $this->app->event->trigger('HttpEnd', $response);
392
393
        // 写入日志
394 1
        $this->app->log->save();
395
        // 写入Session
396 1
        $this->app->session->save();
397 1
    }
398
}
399