Completed
Push — master ( 36f3e7...0844ab )
by Fran
07:51
created

Dispatcher::run()   C

Complexity

Conditions 7
Paths 19

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 13
Bugs 1 Features 1
Metric Value
cc 7
eloc 16
c 13
b 1
f 1
nc 19
nop 0
dl 0
loc 22
rs 6.9811
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 21 and the first side effect is on line 15.

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