Passed
Push — master ( 58ddad...5e153e )
by Fran
03:31
created

Dispatcher::dumpException()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 10
nc 2
nop 1
dl 0
loc 14
ccs 9
cts 9
cp 1
crap 2
rs 9.4285
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
use PSFS\controller\UserController;
20
21 1
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
     * Initializer method
63
     */
64 1
    public function init()
65
    {
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 1
        Logger::log('End dispatcher init');
73 1
    }
74
75
    /**
76
     * Method that assign the locale to the request
77
     * @return $this
78
     */
79 1
    private function setLocale()
80
    {
81 1
        $this->locale = $this->config->get("default_language");
82 1
        Logger::log('Set locale to project [' . $this->locale . ']');
83
        // Load translations
84 1
        putenv("LC_ALL=" . $this->locale);
85 1
        setlocale(LC_ALL, $this->locale);
86
        // 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 1
        textdomain('translations');
92 1
        bind_textdomain_codeset('translations', 'UTF-8');
93
94 1
        return $this;
95
    }
96
97
    /**
98
     * Run method
99
     * @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
        try {
105 5
            if ($this->config->isConfigured()) {
106 4
                if (!$this->parser->isFile()) {
107 4
                    return $this->router->execute($this->actualUri);
108
                }
109
            } else {
110 1
                return ConfigController::getInstance()->config();
111
            }
112 4
        } catch (AdminCredentialsException $a) {
113
            return UserController::showAdminManager();
114 4
        } catch (ConfigException $c) {
115
            return $this->dumpException($c);
116 4
        } catch (SecurityException $s) {
117 1
            return $this->security->notAuthorized($this->actualUri);
118 3
        } catch (UserAuthException $u) {
119
            $this->redirectToHome();
120 3
        } catch (RouterException $r) {
121 1
            return $this->router->httpNotFound($r);
122 2
        } catch (\Exception $e) {
123 2
            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
     * @param \Exception $e
136
     *
137
     * @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
     */
139 2
    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
    {
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
        $error = array(
144 2
            "error" => $ex->getMessage(),
145 2
            "file" => $ex->getFile(),
146 2
            "line" => $ex->getLine(),
147
        );
148 2
        Logger::log('Throwing exception', LOG_ERR, $error);
149 2
        unset($error);
150
151 2
        return $this->router->httpNotFound($ex);
152
    }
153
154
    /**
155
     * Method that returns the memory used at this specific moment
156
     *
157
     * @param $unit string
158
     *
159
     * @return int
160
     */
161 1
    public function getMem($unit = "Bytes")
162
    {
163 1
        $use = memory_get_usage() - $this->mem;
164
        switch ($unit) {
165 1
            case "KBytes":
166 1
                $use /= 1024;
167 1
                break;
168 1
            case "MBytes":
169 1
                $use /= (1024 * 1024);
170 1
                break;
171 1
            case "Bytes":
172
            default:
173
        }
174
175 1
        return $use;
176
    }
177
178
    /**
179
     * Method that returns the seconds spent with the script
180
     * @return double
181
     */
182 3
    public function getTs()
183
    {
184 3
        return microtime(TRUE) - $this->ts;
185
    }
186
187
    /**
188
     * Debug function to catch warnings as exceptions
189
     */
190 1
    protected function bindWarningAsExceptions()
191
    {
192 1
        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
                Logger::log($errstr, LOG_CRIT, ['file' => $errfile, 'line' => $errline]);
197
                throw new \Exception($errstr, 500);
198
            });
199
        }
200 1
    }
201
202
    /**
203
     * Stats initializer
204
     */
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
    {
207 1
        Logger::log('Initializing stats (mem + ts)');
208 1
        if (null !== $_SERVER && array_key_exists('REQUEST_TIME_FLOAT', $_SERVER)) {
209 1
            $this->ts = (float)$_SERVER['REQUEST_TIME_FLOAT'];
210
        } else {
211
            $this->ts = $this->parser->getTs();
212
        }
213 1
        $this->mem = memory_get_usage();
214 1
    }
215
216
}
217