Test Failed
Push — master ( cb8659...54313c )
by Fran
03:21
created

Dispatcher   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 183
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 87.18%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 183
ccs 68
cts 78
cp 0.8718
rs 10
c 2
b 0
f 0
wmc 22
lcom 1
cbo 7

8 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 10 1
A setLocale() 0 17 1
C run() 0 23 8
A dumpException() 0 14 2
A getMem() 0 16 4
A getTs() 0 4 1
A bindWarningAsExceptions() 0 11 2
A initiateStats() 0 10 3
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 25 and the first side effect is on line 19.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * @author Fran López <[email protected]>
4
 * @version 1.0
5
 */
6
7
namespace PSFS;
8
9
use PSFS\base\config\Config;
10
use PSFS\base\exception\ConfigException;
11
use PSFS\base\exception\RouterException;
12
use PSFS\base\exception\SecurityException;
13
use PSFS\base\exception\UserAuthException;
14
use PSFS\base\Logger;
15
use PSFS\base\Request;
16
use PSFS\base\Singleton;
17 1
use PSFS\controller\ConfigController;
18
19
require_once __DIR__ . DIRECTORY_SEPARATOR . "bootstrap.php";
20
21
/**
22
 * Class Dispatcher
23
 * @package PSFS
24
 */
25
class Dispatcher extends Singleton
26
{
27
    /**
28
     * @Inyectable
29
     * @var \PSFS\base\Security $security
30
     */
31
    protected $security;
32
    /**
33
     * @Inyectable
34
     * @var \PSFS\base\Router $router
35
     */
36
    protected $router;
37
    /**
38
     * @Inyectable
39
     * @var \PSFS\base\Request $parser
40
     */
41
    protected $parser;
42
    /**
43
     * @Inyectable
44
     * @var \PSFS\base\Logger $log
45
     */
46
    protected $log;
47
    /**
48
     * @Inyectable
49
     * @var \PSFS\base\config\Config $config
50
     */
51
    protected $config;
52
53
    protected $ts;
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $ts. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
54
    protected $mem;
55
    protected $locale = "es_ES";
56
57
    private $actualUri;
58
59
    /**
60 1
     * Initializer method
61
     */
62 1
    public function init()
63 1
    {
64 1
        Logger::log('Dispatcher init');
65 1
        parent::init();
66 1
        $this->initiateStats();
67 1
        $this->setLocale();
68 1
        $this->bindWarningAsExceptions();
69 1
        $this->actualUri = $this->parser->getServer("REQUEST_URI");
70
        Logger::log('End dispatcher init');
71
    }
72
73
    /**
74
     * Method that assign the locale to the request
75 1
     * @return $this
76
     */
77 1
    private function setLocale()
78 1
    {
79
        $this->locale = $this->config->get("default_language");
80 1
        Logger::log('Set locale to project [' . $this->locale . ']');
81 1
        // Load translations
82
        putenv("LC_ALL=" . $this->locale);
83 1
        setlocale(LC_ALL, $this->locale);
84 1
        // Load the locale path
85 1
        $locale_path = BASE_DIR . DIRECTORY_SEPARATOR . 'locale';
86 1
        Logger::log('Set locale dir ' . $locale_path);
87 1
        Config::createDir($locale_path);
88 1
        bindtextdomain('translations', $locale_path);
89
        textdomain('translations');
90 1
        bind_textdomain_codeset('translations', 'UTF-8');
91
92
        return $this;
93
    }
94
95
    /**
96
     * Run method
97 5
     * @return string HTML
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
98
     */
99 5
    public function run()
100
    {
101 5
        Logger::log('Begin runner');
102 4
        try {
103 4
            if ($this->config->isConfigured()) {
104
                if (!$this->parser->isFile()) {
105
                    return $this->router->execute($this->actualUri);
106 1
                }
107
            } else {
108 4
                return ConfigController::getInstance()->config();
109
            }
110 4
        } catch (ConfigException $c) {
111 1
            return $this->dumpException($c);
112 3
        } catch (SecurityException $s) {
113 2
            return $this->security->notAuthorized($this->actualUri);
114 2
        } catch (UserAuthException $u) {
115 2
            Request::getInstance()->redirect($this->router->getRoute($this->config->get('home_action')));
116
        } catch (RouterException $r) {
117
            return $this->router->httpNotFound($r);
118
        } catch (\Exception $e) {
119
            return $this->dumpException($e);
120
        }
121
    }
122
123
    /**
124
     * Method that convert an exception to html
125
     *
126 2
     * @param \Exception $e
127
     *
128 2
     * @return string HTML
129 2
     */
130
    protected function dumpException(\Exception $e)
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $e. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
131 2
    {
132 2
        Logger::log('Starting dump exception');
133 2
        $ex = (NULL !== $e->getPrevious()) ? $e->getPrevious() : $e;
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $ex. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
134 2
        $error = array(
135 2
            "error" => $ex->getMessage(),
136 2
            "file" => $ex->getFile(),
137
            "line" => $ex->getLine(),
138 2
        );
139
        Logger::log('Throwing exception', LOG_ERR, $error);
140
        unset($error);
141
142
        return $this->router->httpNotFound($ex);
143
    }
144
145
    /**
146
     * Method that returns the memory used at this specific moment
147
     *
148 1
     * @param $unit string
149
     *
150 1
     * @return int
151
     */
152 1
    public function getMem($unit = "Bytes")
153 1
    {
154 1
        $use = memory_get_usage() - $this->mem;
155 1
        switch ($unit) {
156 1
            case "KBytes":
157 1
                $use /= 1024;
158 1
                break;
159 1
            case "MBytes":
160 1
                $use /= (1024 * 1024);
161
                break;
162 1
            case "Bytes":
163
            default:
164
        }
165
166
        return $use;
167
    }
168
169 2
    /**
170
     * Method that returns the seconds spent with the script
171 2
     * @return double
172
     */
173
    public function getTs()
174
    {
175
        return microtime(TRUE) - $this->ts;
176
    }
177 1
178
    /**
179 1
     * Debug function to catch warnings as exceptions
180
     */
181
    protected function bindWarningAsExceptions()
182
    {
183
        if ($this->config->getDebugMode()) {
184
            Logger::log('Added handlers for errors');
185
            //Warning & Notice handler
186
            set_error_handler(function ($errno, $errstr, $errfile, $errline) {
187 1
                Logger::log($errstr, LOG_CRIT, ['file' => $errfile, 'line' => $errline]);
188
                throw new \Exception($errstr, 500);
189
            });
190
        }
191
    }
192 1
193
    /**
194 1
     * Stats initializer
195 1
     */
196 1
    private function initiateStats()
0 ignored issues
show
Coding Style introduced by
initiateStats uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
197 1
    {
198
        Logger::log('Initialicing stats (mem + ts)');
199
        if (null !== $_SERVER && array_key_exists('REQUEST_TIME_FLOAT', $_SERVER)) {
200 1
            $this->ts = (float)$_SERVER['REQUEST_TIME_FLOAT'];
201 1
        } else {
202
            $this->ts = $this->parser->getTs();
203
        }
204
        $this->mem = memory_get_usage();
205
    }
206
207
}
208