Completed
Push — 6.0 ( 54f609...174718 )
by yun
04:30
created

Http::multi()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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

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

322
        $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...
323 5
    }
324
325
    /**
326
     * 加载应用文件
327
     * @param string $appName 应用名
328
     * @return void
329
     */
330 5
    protected function loadApp(string $appName): void
331
    {
332 5
        $this->name = $appName;
333 5
        $this->app->request->setApp($appName);
334 5
        $this->app->setAppPath($this->path ?: $this->app->getBasePath() . $appName . DIRECTORY_SEPARATOR);
335 5
        $this->app->setRuntimePath($this->app->getRootPath() . 'runtime' . DIRECTORY_SEPARATOR . $appName . DIRECTORY_SEPARATOR);
336
337
        //加载app文件
338 5
        if (is_dir($this->app->getAppPath())) {
339 1
            $appPath = $this->app->getAppPath();
340
341 1
            if (is_file($appPath . 'common.php')) {
342 1
                include_once $appPath . 'common.php';
343
            }
344
345 1
            $configPath = $this->app->getConfigPath();
346
347 1
            $files = [];
348
349 1
            if (is_dir($configPath . $appName)) {
350 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

350
                $files = array_merge($files, /** @scrutinizer ignore-type */ glob($configPath . $appName . DIRECTORY_SEPARATOR . '*' . $this->app->getConfigExt()));
Loading history...
351
            } elseif (is_dir($appPath . 'config')) {
352
                $files = array_merge($files, glob($appPath . 'config' . DIRECTORY_SEPARATOR . '*' . $this->app->getConfigExt()));
353
            }
354
355 1
            foreach ($files as $file) {
356
                $this->app->config->load($file, pathinfo($file, PATHINFO_FILENAME));
357
            }
358
359 1
            if (is_file($appPath . 'event.php')) {
360 1
                $this->app->loadEvent(include $appPath . 'event.php');
361
            }
362
363 1
            if (is_file($appPath . 'middleware.php')) {
364 1
                $this->app->middleware->import(include $appPath . 'middleware.php');
365
            }
366
367 1
            if (is_file($appPath . 'provider.php')) {
368 1
                $this->app->bind(include $appPath . 'provider.php');
369
            }
370
        }
371
372
        // 加载应用默认语言包
373 5
        $this->app->loadLangPack($this->app->lang->defaultLangSet());
374
375
        // 设置应用命名空间
376 5
        $this->app->setNamespace($this->app->config->get('app.app_namespace') ?: 'app\\' . $appName);
377 5
    }
378
379
    /**
380
     * HttpEnd
381
     * @param Response $response
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
382
     * @return void
383
     */
384 1
    public function end(Response $response): void
385
    {
386 1
        $this->app->event->trigger('HttpEnd', $response);
387
388
        // 写入日志
389 1
        $this->app->log->save();
390
        // 写入Session
391 1
        $this->app->session->save();
392 1
    }
393
394
    public function __debugInfo()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __debugInfo()
Loading history...
395
    {
396
        return [
397
            'path'       => $this->path,
398
            'multi'      => $this->multi,
399
            'bindDomain' => $this->bindDomain,
400
            'name'       => $this->name,
401
        ];
402
    }
403
}
404