Completed
Push — master ( ec1826...17149c )
by Taosikai
15:14
created

App   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 135
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 0
Metric Value
wmc 14
lcom 1
cbo 10
dl 0
loc 135
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 2
A boot() 0 7 2
A handle() 0 8 1
A terminate() 0 4 1
A serve() 0 9 1
A register() 0 13 3
A getContainer() 0 4 1
A pipe() 0 10 2
A getProviders() 0 4 1
1
<?php
2
3
/*
4
 * This file is part of the jade/jade package.
5
 *
6
 * (c) Slince <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Jade;
13
14
use Jade\Routing\RouteCollector;
15
use Psr\Container\ContainerInterface;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Jade\ContainerInterface.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
16
use Psr\Http\Message\ResponseInterface;
17
use Psr\Http\Message\ServerRequestInterface;
18
use Psr\Http\Server\MiddlewareInterface;
19
use Psr\Http\Server\RequestHandlerInterface;
20
use Jade\HttpKernel\HttpKernelProvider;
21
use Jade\Routing\RouteCollection as RouteCollection;
22
use Jade\Routing\Route;
23
use Jade\Middleware\RouteMiddleware;
24
use Zend\Diactoros\ServerRequestFactory;
25
26
class App extends RouteCollector implements RequestHandlerInterface
27
{
28
    /**
29
     * 是否已经初始化
30
     *
31
     * @var bool
32
     */
33
    protected $booted = false;
34
35
    /**
36
     * @var ContainerInterface
37
     */
38
    protected $container;
39
40
    /**
41
     * @var array
42
     */
43
    protected $providers;
44
45
    public function __construct(ContainerInterface $container = null)
46
    {
47
        if (null === $container) {
48
            $container = new Container();
49
        }
50
        // 注册核心服务
51
        $this->container = $container;
52
        $this->container['app'] = $this;
53
        $this->register(new CoreServiceProvider());
54
        parent::__construct(new RouteCollection());
0 ignored issues
show
Documentation introduced by
new \Jade\Routing\RouteCollection() is of type object<Jade\Routing\RouteCollection>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
55
    }
56
57
    /**
58
     * 初始化启动工作
59
     */
60
    public function boot()
61
    {
62
        if ($this->booted) {
63
            return;
64
        }
65
        $this->booted = true;
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    public function handle(ServerRequestInterface $request): ResponseInterface
72
    {
73
        // 启动应用
74
        $this->boot();
75
        $this->register(new HttpKernelProvider());
76
        // 请求转交给 http kernel
77
        return $this->container->get('http_kernel')->handle($request);
78
    }
79
80
    /**
81
     * 代理http kernel
82
     *
83
     * @param ServerRequestInterface $request
84
     * @param ResponseInterface $response
85
     */
86
    public function terminate(ServerRequestInterface $request, ResponseInterface $response)
87
    {
88
        $this->container->get('http_kernel')->terminate($request, $response);
89
    }
90
91
    /**
92
     * 开启服务, 监听请求
93
     */
94
    public function serve()
95
    {
96
        // 1. 创建请求
97
        $request = ServerRequestFactory::fromGlobals();
98
        // 2. 处理请求
99
        $response = $this->handle($request);
100
        // 3. 输出响应
101
        $this->terminate($request, $response);
102
    }
103
104
    /**
105
     * 注册服务提供者
106
     *
107
     * @param object $provider
108
     * @param array $values
109
     */
110
    public function register($provider, array $values = [])
111
    {
112
        // 注册服务
113
        if ($provider instanceof ServiceProviderInterface) {
114
            $provider->register($this->container);
0 ignored issues
show
Compatibility introduced by
$this->container of type object<Psr\Container\ContainerInterface> is not a sub-type of object<Jade\ContainerInterface>. It seems like you assume a child interface of the interface Psr\Container\ContainerInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
115
        }
116
        // 注册事件
117
        if ($provider instanceof EventProviderInterface) {
118
            $provider->subscribe($this->container->get('event_dispatcher'), $this->container);
0 ignored issues
show
Compatibility introduced by
$this->container of type object<Psr\Container\ContainerInterface> is not a sub-type of object<Jade\ContainerInterface>. It seems like you assume a child interface of the interface Psr\Container\ContainerInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
119
        }
120
        $this->container->merge($values);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Container\ContainerInterface as the method merge() does only exist in the following implementations of said interface: Jade\Container.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
121
        $this->providers[] = $provider;
122
    }
123
124
    /**
125
     * 获取服务容器
126
     *
127
     * @return Container
128
     */
129
    public function getContainer(): Container
130
    {
131
        return $this->container;
132
    }
133
134
    /**
135
     * 添加一个 middleware
136
     *
137
     * @param string|MiddlewareInterface|callable $middleware
138
     * @param Route|null $route 绑定的路由
139
     */
140
    public function pipe($middleware, Route $route = null)
141
    {
142
        $middleware = $this->container->get('middleware_factory')->create($middleware);
143
        if (null !== $route) {
144
            $middleware = new RouteMiddleware($route, $middleware);
145
        }
146
        $this->container->get('middleware_pipeline')->pipe(
147
            $middleware
148
        );
149
    }
150
151
    /**
152
     * 返回全部的 provider
153
     *
154
     * @return array
155
     */
156
    public function getProviders()
157
    {
158
        return $this->providers;
159
    }
160
}