Test Failed
Push — master ( c8eeb1...8dcff2 )
by Fran
03:30
created

Dispatcher::run()   D

Complexity

Conditions 9
Paths 27

Size

Total Lines 25
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 11.551

Importance

Changes 0
Metric Value
cc 9
eloc 20
nc 27
nop 0
dl 0
loc 25
ccs 13
cts 19
cp 0.6842
crap 11.551
rs 4.909
c 0
b 0
f 0
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 27 and the first side effect is on line 21.

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