Passed
Push — develop ( 91c1d2...446210 )
by Schlaefer
41s
created

Phile::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
/**
3
 * @author  PhileCMS
4
 * @link    https://philecms.com
5
 * @license http://opensource.org/licenses/MIT
6
 */
7
8
namespace Phile;
9
10
use Phile\Core\Config;
11
use Phile\Core\Container;
12
use Phile\Core\Event;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Phile\Event.

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...
13
use Phile\Core\RequestHandler;
14
use Phile\Core\Response;
15
use Phile\Core\Router;
16
use Phile\Model\Page;
17
use Phile\Repository\Page as Repository;
18
19
use Interop\Http\Server\MiddlewareInterface;
20
use Interop\Http\Server\RequestHandlerInterface;
21
use Psr\Http\Message\ResponseInterface;
22
use Psr\Http\Message\ServerRequestInterface;
23
24
/**
25
 * Phile Core class
26
 */
27
class Phile implements MiddlewareInterface
28
{
29
    /** @var Config Phile configuration */
30
    protected $config;
31
32
    /** @var Event event-bus */
33
    protected $eventBus;
34
35
    /** @var array callbacks run at bootstrap */
36
    protected $bootstrapConfigs = [];
37
38
    /** @var array callbacks run on middleware-setup */
39
    protected $middlewareConfigs = [];
40
41
    /**
42
     * Constructor sets-up base Phile environment
43
     *
44
     * @param Event $eventBus
45
     * @param Config $config
46
     */
47 27
    public function __construct(Event $eventBus, Config $config)
48
    {
49 27
        $this->eventBus = $eventBus;
50 27
        $this->config = $config;
51 27
    }
52
53
    /**
54
     * Adds bootstrap-setup
55
     */
56 27
    public function addBootstrap(callable $bootstrap)
57
    {
58 27
        $this->bootstrapConfigs[] = $bootstrap;
59 27
        return $this;
60
    }
61
62
    /**
63
     * Adds middleware-setup
64
     */
65 27
    public function addMiddleware(callable $middleware)
66
    {
67 27
        $this->middlewareConfigs[] = $middleware;
68 27
        return $this;
69
    }
70
71
    /**
72
     * Performs bootstrap
73
     */
74 26
    public function bootstrap()
75
    {
76 26
        foreach ($this->bootstrapConfigs as $config) {
77 26
            call_user_func_array($config, [$this->eventBus, $this->config]);
78
        }
79 26
        return $this;
80
    }
81
82
    /**
83
     * Processes request
84
     */
85 4
    public function dispatch($request)
86
    {
87 4
        $this->bootstrap();
88 4
        $this->config->lock();
89
90 4
        $requestHandler = new RequestHandler(new Response);
91 4
        foreach ($this->middlewareConfigs as $config) {
92 4
            call_user_func_array($config, [$requestHandler, $this->eventBus, $this->config]);
93
        }
94
95 4
        return $requestHandler->handle($request);
96
    }
97
98
    /**
99
     * Implements PSR-15 middle-ware process-handler
100
     */
101 4
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler)
102
    {
103 4
        $router = new Router($request->getServerParams());
104 4
        Container::getInstance()->set('Phile_Router', $router);
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 set() does only exist in the following implementations of said interface: Phile\Core\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...
105
106
        // BC: send response in after_init_core event
107 4
        $response = new Response;
108 4
        $response->setCharset($this->config->get('charset'));
109 4
        $this->eventBus->trigger('after_init_core', ['response' => &$response]);
110 4
        if ($response instanceof ResponseInterface) {
111 1
            return $response;
112
        }
113
114 4
        $page = $this->resolveCurrentPage($router);
115 4
        if ($page instanceof ResponseInterface) {
116 2
            return $page;
117
        }
118
119 3
        $html = $this->renderHtml($page);
0 ignored issues
show
Bug introduced by
It seems like $page defined by $this->resolveCurrentPage($router) on line 114 can be null; however, Phile\Phile::renderHtml() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
120 3
        if ($html instanceof ResponseInterface) {
121 1
            return $html;
122
        }
123
124 2
        $charset = $this->config->get('charset');
125 2
        $response = (new Response)->createHtmlResponse($html)
126 2
            ->withHeader('Content-Type', 'text/html; charset=' . $charset);
127
128 2
        if ($page->getPageId() == '404') {
129 1
            $response = $response->withStatus(404) ;
130
        }
131
132 2
        return $response;
133
    }
134
135
    /**
136
     * Resolves request into the current page
137
     */
138 4
    protected function resolveCurrentPage(Router $router)
139
    {
140 4
        $pageId = $router->getCurrentUrl();
141 4
        $response = null;
142 4
        $this->eventBus->trigger(
143 4
            'request_uri',
144 4
            ['uri' => $pageId, 'response' => &$response]
145
        );
146 4
        if ($response instanceof ResponseInterface) {
147 1
            return $response;
148
        }
149
150 4
        $repository = new Repository();
151 4
        $page = $repository->findByPath($pageId);
152 4
        $found = $page instanceof Page;
153
154 4
        if ($found && $pageId !== $page->getPageId()) {
155 1
            $url = $router->urlForPage($page->getPageId());
156 1
            return (new Response)->createRedirectResponse($url, 301);
157
        }
158
159 3
        if (!$found) {
160 1
            $page = $repository->findByPath('404');
161 1
            $this->eventBus->trigger('after_404');
162
        }
163
164 3
        $this->eventBus->trigger(
165 3
            'after_resolve_page',
166 3
            ['pageId' => $pageId, 'page' => &$page, 'response' => &$response]
167
        );
168 3
        if ($response instanceof ResponseInterface) {
169 1
            return $response;
170
        }
171
172 3
        return $page;
173
    }
174
175
    /**
176
     * Renders page into output format (HTML)
177
     */
178 3
    protected function renderHtml(Page $page)
179
    {
180 3
        $this->eventBus->trigger('before_init_template');
181 3
        $engine = ServiceLocator::getService('Phile_Template');
182
183 3
        $coreVars = $this->config->getTemplateVars();
184 3
        $templateVars = Registry::get('templateVars') + $coreVars;
185 3
        Registry::set('templateVars', $templateVars);
186
187 3
        $response = null;
188 3
        $this->eventBus->trigger(
189 3
            'before_render_template',
190 3
            ['templateEngine' => &$engine, 'response' => &$response]
191
        );
192 3
        if ($response instanceof ResponseInterface) {
193 1
            return $response;
194
        }
195
196 2
        $engine->setCurrentPage($page);
197 2
        $html = $engine->render();
198
199 2
        $this->eventBus->trigger(
200 2
            'after_render_template',
201 2
            ['templateEngine' => &$engine, 'output' => &$html]
202
        );
203
204 2
        return $html;
205
    }
206
}
207