Dispatcher::setLogger()   A
last analyzed

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
declare(strict_types = 1);
3
4
namespace Zortje\MVC\Routing;
5
6
use Monolog\Logger;
7
use Zortje\MVC\Configuration\Configuration;
8
use Zortje\MVC\Controller\ControllerFactory;
9
use Zortje\MVC\Controller\Exception\ControllerActionPrivateInsufficientAuthenticationException;
10
use Zortje\MVC\Controller\Exception\ControllerActionProtectedInsufficientAuthenticationException;
11
use Zortje\MVC\Controller\NotFoundController; // @todo this is a user implemented controller and should be removed after user stuff is cleaned up
12
use Zortje\MVC\Model\Table\Entity\Entity;
13
use Zortje\MVC\Network\Request;
14
use Zortje\MVC\Network\Response;
15
use Zortje\MVC\Routing\Exception\RouteNonexistentException;
16
17
/**
18
 * Class Dispatcher
19
 *
20
 * @package Zortje\MVC\Routing
21
 */
22
class Dispatcher
23
{
24
25
    /**
26
     * @var \PDO PDO
27
     */
28
    protected $pdo;
29
30
    /**
31
     * @var Configuration Configuration
32
     */
33
    protected $configuration;
34
35
    /**
36
     * @var Logger
37
     */
38
    protected $logger;
39
40
    /**
41
     * Dispatcher constructor.
42
     *
43
     * @param \PDO          $pdo
44
     * @param Configuration $configuration
45
     */
46 1
    public function __construct(\PDO $pdo, Configuration $configuration)
47
    {
48 1
        $this->pdo           = $pdo;
49 1
        $this->configuration = $configuration;
50 1
    }
51
52
    /**
53
     * Set logger to be used for any logging that could occure in the dispatching process
54
     *
55
     * @param Logger $logger
56
     */
57 1
    public function setLogger(Logger $logger)
58
    {
59 1
        $this->logger = $logger;
60 1
    }
61
62
    /**
63
     * @param Request     $request Request object
64
     * @param Entity|null $user
65
     *
66
     * @return Response Reponse object
67
     *
68
     * @throws \Exception If unexpected exception is thrown
69
     */
70 1
    public function dispatch(Request $request, Entity $user = null): Response
71
    {
72 1
        $controllerFactory = new ControllerFactory($this->pdo, $this->configuration, $request, $user);
73
74
        /**
75
         * Figure out what controller to use and what action to call
76
         */
77
        try {
78
            /**
79
             * @var Router $router
80
             */
81 1
            $router = $this->configuration->get('Router');
82
83 1
            list($controllerName, $action, $arguments) = array_values($router->route($request->getPath()));
84
85
            /**
86
             * Validate and initialize controller
87
             */
88 1
            $controller = $controllerFactory->create($controllerName);
89
        } catch (RouteNonexistentException $e) {
90
            /**
91
             * Log nonexistent route (404)
92
             */
93
            if ($this->logger) {
94
                $this->logger->addWarning('Route not connected', [
95
                    'path' => $request->getPath()
96
                ]);
97
            }
98
99
            $controller = $controllerFactory->create(NotFoundController::class);
100
            $action     = 'index';
101
            $arguments  = [];
102
        }
103
104
        /**
105
         * Set arguments
106
         */
107 1
        $controller->setArguments($arguments);
108
109
        /**
110
         * Validate and set controller action
111
         */
112
        try {
113 1
            $controller->setAction($action);
114
        } catch (ControllerActionProtectedInsufficientAuthenticationException $e) {
115
            /**
116
             * Log unauthed protected controller action (403)
117
             */
118 View Code Duplication
            if ($this->logger) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
119
                $this->logger->addWarning('Unauthenticated attempt to access protected action', [
120
                    'path'       => $request->getPath(),
121
                    'controller' => $controller->getShortName(),
122
                    'action'     => $action
123
                ]);
124
            }
125
126
            if ($this->configuration->exists('User.SignIn.Controller.Class') && $this->configuration->exists('User.SignIn.Controller.Action')) {
127
                /**
128
                 * Save what controller and action was requested and then redirect to sign in form
129
                 */
130
                // @todo test that this works
131
                $request->getCookie()->set('SignIn.onSuccess.path', $request->getPath());
132
133
                $controller = $controllerFactory->create($this->configuration->get('User.SignIn.Controller.Class'));
134
                $controller->setAction($this->configuration->get('User.SignIn.Controller.Action'));
135
            } else {
136
                $controller = $controllerFactory->create(NotFoundController::class);
137
                $controller->setAction('index');
138
            }
139
        } catch (ControllerActionPrivateInsufficientAuthenticationException $e) {
140
            /**
141
             * Log unauthed private controller action (403)
142
             */
143 View Code Duplication
            if ($this->logger) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
144
                $this->logger->addWarning('Unauthenticated attempt to access private action', [
145
                    'path'       => $request->getPath(),
146
                    'controller' => $controller->getShortName(),
147
                    'action'     => $action
148
                ]);
149
            }
150
        }
151
152
        /**
153
         * Create response from controller action headers and output
154
         */
155 1
        $response = $controller->callAction();
156
157
        /**
158
         * Performance logging
159
         */
160 1
        if ($this->logger) {
161
            $time = number_format((microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']) * 1000, 2); // @todo $_SERVER usage
162
163
            $this->logger->addDebug("Dispatched request in $time ms", ['path' => $request->getPath()]);
164
        }
165
166 1
        return $response;
167
    }
168
}
169