Completed
Push — master ( 8a02a1...c877ec )
by Fran
04:56 queued 14s
created

Dispatcher   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 180
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 88.46%

Importance

Changes 19
Bugs 1 Features 2
Metric Value
c 19
b 1
f 2
dl 0
loc 180
rs 10
ccs 69
cts 78
cp 0.8846
wmc 21
lcom 1
cbo 7

8 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 10 1
A setLocale() 0 17 1
B run() 0 21 7
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 22 and the first side effect is on line 16.

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\Logger;
14
use PSFS\base\Singleton;
15
16 1
require_once __DIR__ . DIRECTORY_SEPARATOR . "bootstrap.php";
17
18
/**
19
 * Class Dispatcher
20
 * @package PSFS
21
 */
22
class Dispatcher extends Singleton
23
{
24
    /**
25
     * @Inyectable
26
     * @var \PSFS\base\Security $security
27
     */
28
    protected $security;
29
    /**
30
     * @Inyectable
31
     * @var \PSFS\base\Router $router
32
     */
33
    protected $router;
34
    /**
35
     * @Inyectable
36
     * @var \PSFS\base\Request $parser
37
     */
38
    protected $parser;
39
    /**
40
     * @Inyectable
41
     * @var \PSFS\base\Logger $log
42
     */
43
    protected $log;
44
    /**
45
     * @Inyectable
46
     * @var \PSFS\base\config\Config $config
47
     */
48
    protected $config;
49
50
    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...
51
    protected $mem;
52
    protected $locale = "es_ES";
53
54
    private $actualUri;
55
56
    /**
57
     * Initializer method
58
     */
59 1
    public function init()
60
    {
61 1
        Logger::log('Dispatcher init');
62 1
        parent::init();
63 1
        $this->initiateStats();
64 1
        $this->setLocale();
65 1
        $this->bindWarningAsExceptions();
66 1
        $this->actualUri = $this->parser->getServer("REQUEST_URI");
67 1
        Logger::log('End dispatcher init');
68 1
    }
69
70
    /**
71
     * Method that assign the locale to the request
72
     * @return $this
73
     */
74 1
    private function setLocale()
75
    {
76 1
        $this->locale = $this->config->get("default_language");
77 1
        Logger::log('Set locale to project [' . $this->locale . ']');
78
        // Load translations
79 1
        putenv("LC_ALL=" . $this->locale);
80 1
        setlocale(LC_ALL, $this->locale);
81
        // Load the locale path
82 1
        $locale_path = BASE_DIR . DIRECTORY_SEPARATOR . 'locale';
83 1
        Logger::log('Set locale dir ' . $locale_path);
84 1
        Config::createDir($locale_path);
85 1
        bindtextdomain('translations', $locale_path);
86 1
        textdomain('translations');
87 1
        bind_textdomain_codeset('translations', 'UTF-8');
88
89 1
        return $this;
90
    }
91
92
    /**
93
     * Run method
94
     */
95 5
    public function run()
96
    {
97 5
        Logger::log('Begin runner');
98
        try {
99 5
            if ($this->config->isConfigured()) {
100 4
                if (!$this->parser->isFile()) {
101 4
                    return $this->router->execute($this->actualUri);
102
                }
103
            } else {
104 1
                return $this->router->getAdmin()->config();
105
            }
106 4
        } catch (ConfigException $c) {
107 1
            return $this->dumpException($c);
108 3
        } catch (SecurityException $s) {
109 1
            return $this->security->notAuthorized($this->actualUri);
110 2
        } catch (RouterException $r) {
111 1
            return $this->router->httpNotFound($r);
112 1
        } catch (\Exception $e) {
113 1
            return $this->dumpException($e);
114
        }
115
    }
116
117
    /**
118
     * Method that convert an exception to html
119
     *
120
     * @param \Exception $e
121
     *
122
     * @return string HTML
123
     */
124 3
    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...
125
    {
126 2
        Logger::log('Starting dump exception');
127 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...
128
        $error = array(
129 3
            "error" => $ex->getMessage(),
130 2
            "file" => $ex->getFile(),
131 2
            "line" => $ex->getLine(),
132 2
        );
133 2
        Logger::log('Throwing exception', LOG_ERR, $error);
134 2
        unset($error);
135
136 2
        return $this->router->httpNotFound($ex);
137
    }
138
139
    /**
140
     * Method that returns the memory used at this specific moment
141
     *
142
     * @param $unit string
143
     *
144
     * @return int
145
     */
146 1
    public function getMem($unit = "Bytes")
147
    {
148 1
        $use = memory_get_usage() - $this->mem;
149
        switch ($unit) {
150 1
            case "KBytes":
151 1
                $use /= 1024;
152 1
                break;
153 1
            case "MBytes":
154 1
                $use /= (1024 * 1024);
155 1
                break;
156 1
            case "Bytes":
157 1
            default:
158 1
        }
159
160 1
        return $use;
161
    }
162
163
    /**
164
     * Method that returns the seconds spent with the script
165
     * @return double
166
     */
167 2
    public function getTs()
168
    {
169 2
        return microtime(TRUE) - $this->ts;
170
    }
171
172
    /**
173
     * Debug function to catch warnings as exceptions
174
     */
175 1
    protected function bindWarningAsExceptions()
176
    {
177 1
        if ($this->config->getDebugMode()) {
178
            Logger::log('Added handlers for errors');
179
            //Warning & Notice handler
180
            set_error_handler(function ($errno, $errstr, $errfile, $errline) {
181
                Logger::log($errstr, LOG_CRIT, ['file' => $errfile, 'line' => $errline]);
182
                throw new \Exception($errstr, 500);
183
            });
184
        }
185 1
    }
186
187
    /**
188
     * Stats initializer
189
     */
190 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...
191
    {
192 1
        Logger::log('Initialicing stats (mem + ts)');
193 1
        if (null !== $_SERVER && array_key_exists('REQUEST_TIME_FLOAT', $_SERVER)) {
194 1
            $this->ts = (float)$_SERVER['REQUEST_TIME_FLOAT'];
195 1
        } else {
196
            $this->ts = $this->parser->getTs();
197
        }
198 1
        $this->mem = memory_get_usage();
199 1
    }
200
201
}
202