Passed
Push — master ( a14261...5f8bab )
by Gabor
05:22
created

ServiceAdapter::__construct()   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
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * WebHemi.
4
 *
5
 * PHP version 7.1
6
 *
7
 * @copyright 2012 - 2017 Gixx-web (http://www.gixx-web.com)
8
 * @license   https://opensource.org/licenses/MIT The MIT License (MIT)
9
 *
10
 * @link      http://www.gixx-web.com
11
 */
12
declare(strict_types = 1);
13
14
namespace WebHemi\Application\ServiceAdapter\Base;
15
16
use WebHemi\Application\ServiceAdapter\AbstractAdapter;
17
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
18
use WebHemi\Http\ResponseInterface;
19
use WebHemi\Http\ServerRequestInterface;
20
use WebHemi\Http\ServiceInterface as HttpInterface;
21
use WebHemi\MiddlewarePipeline\ServiceInterface as PipelineInterface;
22
use WebHemi\Middleware\Common as CommonMiddleware;
23
use WebHemi\Session\ServiceInterface as SessionInterface;
24
25
/**
26
 * Class ServiceAdapter
27
 */
28
class ServiceAdapter extends AbstractAdapter
29
{
30
    /**
31
     * Starts the session.
32
     *
33
     * @return void
34
     *
35
     * @codeCoverageIgnore - not testing session (yet)
36
     */
37
    protected function initSession() : void
38
    {
39
        if (defined('PHPUNIT_WEBHEMI_TESTSUITE')) {
40
            return;
41
        }
42
43
        /** @var SessionInterface $sessionManager */
44
        $sessionManager = $this->container->get(SessionInterface::class);
45
        /** @var EnvironmentInterface $environmentManager */
46
        $environmentManager = $this->container->get(EnvironmentInterface::class);
47
48
        $name = $environmentManager->getSelectedApplication();
49
        $timeOut = 3600;
50
        $path = $environmentManager->getSelectedApplicationUri();
51
        $domain = $environmentManager->getApplicationDomain();
52
        $secure = $environmentManager->isSecuredApplication();
53
        $httpOnly = true;
54
55
        $sessionManager->start($name, $timeOut, $path, $domain, $secure, $httpOnly);
56
    }
57
58
    /**
59
     * Runs the application. This is where the magic happens.
60
     * According tho the environment settings this must build up the middleware pipeline and execute it.
61
     *
62
     * a Pre-Routing Middleware can be; priority < 0:
63
     *  - LockCheck - check if the client IP is banned > S102|S403
64
     *  - Auth - if the user is not logged in, but there's a "Remember me" cookie, then logs in > S102
65
     *
66
     * Routing Middleware is fixed (RoutingMiddleware::class); priority = 0:
67
     *  - A middleware that routes the incoming Request and delegates to the matched middleware. > S102|S404|S405
68
     *    The RouteResult should be attached to the Request.
69
     *    If the Routing is not defined explicitly in the pipeline, then it will be injected with priority 0.
70
     *
71
     * a Post-Routing Middleware can be; priority between 0 and 100:
72
     *  - Acl - checks if the given route is available for the client. Also checks the auth > S102|S401|S403
73
     *  - CacheReader - checks if a suitable response body is cached. > S102|S200
74
     *
75
     * Dispatcher Middleware is fixed (DispatcherMiddleware::class); priority = 100:
76
     *  - A middleware which gets the corresponding Action middleware and applies it > S102
77
     *    If the Dispatcher is not defined explicitly in the pipeline, then it will be injected with priority 100.
78
     *    The Dispatcher should not set the response Status Code to 200 to let Post-Dispatchers to be called.
79
     *
80
     * a Post-Dispatch Middleware can be; priority > 100:
81
     *  - CacheWriter - writes response body into DataStorage (DB, File etc.) > S102
82
     *
83
     * Final Middleware is fixed (FinalMiddleware:class):
84
     *  - This middleware behaves a bit differently. It cannot be ordered, it's always the last called middleware:
85
     *    - when the middleware pipeline reached its end (typically when the Status Code is still 102)
86
     *    - when one item of the middleware pipeline returns with return response (status code is set to 200|40*|500)
87
     *    - when during the pipeline process an Exception is thrown.
88
     *
89
     * When the middleware pipeline is finished the application prints the header and the output.
90
     *
91
     * If a middleware other than the Routing, Dispatcher and Final Middleware has no priority set, it will be
92
     * considered to have priority = 50.
93
     *
94
     * @return void
95
     */
96 5
    public function run() : void
97
    {
98
        // Start session.
99 5
        $this->initSession();
100
101
        /** @var PipelineInterface $pipelineManager */
102 5
        $pipelineManager = $this->container->get(PipelineInterface::class);
103 5
        $request = $this->getRequest();
104 5
        $response = $this->getResponse();
105
106
        /** @var string $middlewareClass */
107 5
        $middlewareClass = $pipelineManager->start();
108
109 5
        while ($middlewareClass !== null
110 5
            && $response->getStatusCode() == ResponseInterface::STATUS_PROCESSING
111
        ) {
112 5
            $this->invokeMiddleware($middlewareClass, $request, $response);
113 5
            $middlewareClass = $pipelineManager->next();
114
        };
115
116
        // If there was no error, we mark as ready for output.
117 5
        if ($response->getStatusCode() == ResponseInterface::STATUS_PROCESSING) {
118 1
            $response = $response->withStatus(ResponseInterface::STATUS_OK);
119
        }
120
121
        /** @var CommonMiddleware\FinalMiddleware $finalMiddleware */
122 5
        $finalMiddleware = $this->container->get(CommonMiddleware\FinalMiddleware::class);
123
124
        // Send out headers and content.
125 5
        $finalMiddleware($request, $response);
126 5
    }
127
128
    /**
129
     * Gets the Request object.
130
     *
131
     * @return ServerRequestInterface
132
     */
133 5
    protected function getRequest() : ServerRequestInterface
134
    {
135
        /** @var HttpInterface $httpAdapter */
136 5
        $httpAdapter = $this->container->get(HttpInterface::class);
137
        /** @var EnvironmentInterface $environmentManager */
138 5
        $environmentManager = $this->container->get(EnvironmentInterface::class);
139
140
        /** @var ServerRequestInterface $request */
141 5
        $request = $httpAdapter->getRequest()
142 5
            ->withAttribute(
143 5
                ServerRequestInterface::REQUEST_ATTR_DISPATCH_DATA,
144
                [
145 5
                    'selected_module' => $environmentManager->getSelectedModule(),
146 5
                    'application_domain' => 'http'.($environmentManager->isSecuredApplication() ? 's' : '')
147 5
                        .'://'
148 5
                        .$environmentManager->getApplicationDomain()
149
                ]
150
            );
151
152 5
        return $request;
153
    }
154
155
    /**
156
     * Gets the Response object.
157
     *
158
     * @return ResponseInterface
159
     */
160 5
    protected function getResponse() : ResponseInterface
161
    {
162
        /** @var HttpInterface $httpAdapter */
163 5
        $httpAdapter = $this->container->get(HttpInterface::class);
164
165
        /** @var ResponseInterface $response */
166 5
        return $httpAdapter->getResponse();
167
    }
168
}
169