Completed
Pull Request — master (#2)
by René
04:42
created

Dispatcher   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 141
Duplicated Lines 9.93 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 0%

Importance

Changes 17
Bugs 0 Features 0
Metric Value
wmc 12
c 17
b 0
f 0
lcom 1
cbo 7
dl 14
loc 141
ccs 0
cts 59
cp 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A setLogger() 0 4 1
C dispatch() 14 92 10

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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