Completed
Push — master ( 04bd65...4036d4 )
by Fran
09:06
created

Dispatcher::initiateStats()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 10
ccs 7
cts 8
cp 0.875
crap 3.0175
rs 9.4285
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
            Logger::log('Set locale to project');
77 1
            $this->locale = $this->config->get("default_language");
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
            Config::createDir($locale_path);
84 1
            bindtextdomain('translations', $locale_path);
85 1
            textdomain('translations');
86 1
            bind_textdomain_codeset('translations', 'UTF-8');
87
88 1
            return $this;
89
        }
90
91
        /**
92
         * Run method
93
         */
94 5
        public function run()
95
        {
96 5
            Logger::log('Begin runner');
97
            try {
98 5
                if ($this->config->isConfigured()) {
99 4
                    if (!$this->parser->isFile()) {
100 4
                        return $this->router->execute($this->actualUri);
101
                    }
102
                } else {
103 1
                    return $this->router->getAdmin()->config();
104
                }
105 4
            } catch (ConfigException $c) {
106 1
                return $this->dumpException($c);
107 3
            } catch (SecurityException $s) {
108 1
                return $this->security->notAuthorized($this->actualUri);
109 2
            } catch (RouterException $r) {
110 1
                return $this->router->httpNotFound($r);
111 1
            } catch (\Exception $e) {
112 1
                return $this->dumpException($e);
113
            }
114
        }
115
116
        /**
117
         * Method that convert an exception to html
118
         *
119
         * @param \Exception $e
120
         *
121
         * @return string HTML
122
         */
123 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...
124
        {
125 2
            Logger::log('Starting dump exception');
126 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...
127
            $error = array(
128 2
                "error" => $ex->getMessage(),
129 2
                "file"  => $ex->getFile(),
130 2
                "line"  => $ex->getLine(),
131 2
            );
132 2
            Logger::log('Throwing exception', LOG_ERR, $error);
133 2
            unset($error);
134
135 2
            return $this->router->httpNotFound($ex);
136
        }
137
138
        /**
139
         * Method that returns the memory used at this specific moment
140
         *
141
         * @param $unit string
142
         *
143
         * @return int
144
         */
145 1
        public function getMem($unit = "Bytes")
146
        {
147 1
            $use = memory_get_usage() - $this->mem;
148
            switch ($unit) {
149 1
                case "KBytes":
150 1
                    $use /= 1024;
151 1
                    break;
152 1
                case "MBytes":
153 1
                    $use /= (1024 * 1024);
154 1
                    break;
155 1
                case "Bytes":
156 1
                default:
157 1
            }
158
 
159 1
            return $use;
160
        }
161
162
        /**
163
         * Method that returns the seconds spent with the script
164
         * @return double
165
         */
166 2
        public function getTs()
167
        {
168 2
            return microtime(TRUE) - $this->ts;
169
        }
170
171
        /**
172
         * Debug function to catch warnings as exceptions
173
         */
174 1
        protected function bindWarningAsExceptions()
175
        {
176 1
            if ($this->config->getDebugMode()) {
177 1
                Logger::log('Added handlers for errors');
178
                //Warning & Notice handler
179 1
                set_error_handler(function ($errno, $errstr, $errfile, $errline) {
180
                    Logger::log($errstr, LOG_CRIT, ['file' => $errfile, 'line' => $errline]);
181
                    throw new \Exception($errstr, 500);
182 1
                });
183 1
            }
184 1
        }
185
186
        /**
187
         * Stats initializer
188
         */
189 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...
190
        {
191 1
            Logger::log('Initialicing stats (mem + ts)');
192 1
            if(null !== $_SERVER && array_key_exists('REQUEST_TIME_FLOAT', $_SERVER)) {
193 1
                $this->ts = (float)$_SERVER['REQUEST_TIME_FLOAT'];
194 1
            } else {
195
                $this->ts = $this->parser->getTs();
196
            }
197 1
            $this->mem = memory_get_usage();
198 1
        }
199
200
    }
201