Completed
Pull Request — master (#2)
by René
04:34 queued 02:28
created

Dispatcher::dispatch()   C

Complexity

Conditions 10
Paths 98

Size

Total Lines 92
Code Lines 38

Duplication

Lines 14
Ratio 15.22 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 15
Bugs 0 Features 0
Metric Value
c 15
b 0
f 0
dl 14
loc 92
ccs 0
cts 50
cp 0
rs 5.0865
cc 10
eloc 38
nc 98
nop 2
crap 110

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
    public function __construct(\PDO $pdo, Configuration $configuration)
47
    {
48
        $this->pdo           = $pdo;
49
        $this->configuration = $configuration;
50
    }
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
    public function setLogger(Logger $logger)
58
    {
59
        $this->logger = $logger;
60
    }
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
    public function dispatch(Request $request, Entity $user = null): Response
71
    {
72
        $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
            $router = $this->configuration->get('Router');
82
83
            list($controllerName, $action) = array_values($router->route($request->getPath()));
84
85
            /**
86
             * Validate and initialize controller
87
             */
88
            $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
        }
102
103
        /**
104
         * Validate and set controller action
105
         */
106
        try {
107
            $controller->setAction($action);
108
        } catch (ControllerActionProtectedInsufficientAuthenticationException $e) {
109
            /**
110
             * Log unauthed protected controller action (403)
111
             */
112 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...
113
                $this->logger->addWarning('Unauthenticated attempt to access protected action', [
114
                    'path'       => $request->getPath(),
115
                    'controller' => $controller->getShortName(),
116
                    'action'     => $action
117
                ]);
118
            }
119
120
            if ($this->configuration->exists('User.SignIn.Controller.Class') && $this->configuration->exists('User.SignIn.Controller.Action')) {
121
                /**
122
                 * Save what controller and action was requested and then redirect to sign in form
123
                 */
124
                // @todo test that this works
125
                $request->getCookie()->set('SignIn.onSuccess.path', $request->getPath());
126
127
                $controller = $controllerFactory->create($this->configuration->get('User.SignIn.Controller.Class'));
128
                $controller->setAction($this->configuration->get('User.SignIn.Controller.Action'));
129
            } else {
130
                $controller = $controllerFactory->create(NotFoundController::class);
131
                $controller->setAction('index');
132
            }
133
        } catch (ControllerActionPrivateInsufficientAuthenticationException $e) {
134
            /**
135
             * Log unauthed private controller action (403)
136
             */
137 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...
138
                $this->logger->addWarning('Unauthenticated attempt to access private action', [
139
                    'path'       => $request->getPath(),
140
                    'controller' => $controller->getShortName(),
141
                    'action'     => $action
142
                ]);
143
            }
144
        }
145
146
        /**
147
         * Create response from controller action headers and output
148
         */
149
        $response = $controller->callAction();
150
151
        /**
152
         * Performance logging
153
         */
154
        if ($this->logger) {
155
            $time = number_format((microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']) * 1000, 2);
156
157
            $this->logger->addDebug("Dispatched request in $time ms", ['path' => $request->getPath()]);
158
        }
159
160
        return $response;
161
    }
162
}
163