Test Failed
Push — master ( 48e4aa...acaa8d )
by Fran
02:55
created

Router::execute()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.1967

Importance

Changes 0
Metric Value
cc 4
eloc 13
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 18
ccs 10
cts 13
cp 0.7692
crap 4.1967
rs 9.8333
1
<?php
2
3
namespace PSFS\base;
4
5
use Exception;
6
use InvalidArgumentException;
7
use PSFS\base\config\Config;
8
use PSFS\base\exception\AccessDeniedException;
9
use PSFS\base\exception\AdminCredentialsException;
10
use PSFS\base\exception\ConfigException;
11
use PSFS\base\exception\GeneratorException;
12
use PSFS\base\exception\RouterException;
13
use PSFS\base\types\Controller;
14
use PSFS\base\types\helpers\GeneratorHelper;
15
use PSFS\base\types\helpers\Inspector;
16
use PSFS\base\types\helpers\ResponseHelper;
17
use PSFS\base\types\helpers\RouterHelper;
18
use PSFS\base\types\helpers\SecurityHelper;
19
use PSFS\base\types\traits\Router\ModulesTrait;
20
use PSFS\base\types\traits\SingletonTrait;
21
use PSFS\controller\base\Admin;
22
use ReflectionException;
23
24
/**
25
 * Class Router
26
 * @package PSFS
27
 */
28
class Router
29
{
30
    use SingletonTrait;
31
    use ModulesTrait;
32
33
    const PSFS_BASE_NAMESPACE = 'PSFS';
34
    /**
35
     * @var Cache $cache
36
     */
37
    private $cache;
38
    /**
39
     * @var int
40
     */
41
    protected $cacheType = Cache::JSON;
42
43
    /**
44
     * Router constructor.
45
     * @throws GeneratorException
46
     * @throws ConfigException
47
     * @throws InvalidArgumentException
48
     * @throws ReflectionException
49
     */
50 4
    public function __construct()
51
    {
52 4
        $this->cache = Cache::getInstance();
53 4
        $this->initializeFinder();
54 4
        $this->init();
55
    }
56
57
    /**
58
     * @throws GeneratorException
59
     * @throws ConfigException
60
     * @throws InvalidArgumentException
61
     * @throws ReflectionException
62
     */
63 5
    public function init()
64
    {
65 5
        list($this->routing, $this->slugs) = $this->cache->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . 'urls.json', $this->cacheType, TRUE);
66 5
        $this->domains = $this->cache->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . 'domains.json', $this->cacheType, TRUE);
67 5
        if (empty($this->routing) || Config::getParam('debug', true)) {
68 5
            $this->debugLoad();
69
        }
70 5
        $this->checkExternalModules(false);
71 5
        $this->setLoaded();
72
    }
73
74
    /**
75
     * @throws GeneratorException
76
     * @throws ConfigException
77
     * @throws InvalidArgumentException
78
     * @throws ReflectionException
79
     */
80 5
    private function debugLoad()
81
    {
82 5
        Logger::log('Begin routes load');
83 5
        $this->hydrateRouting();
84 5
        $this->simpatize();
85 5
        Logger::log('End routes load');
86
    }
87
88
    /**
89
     * @param string|null $route
90
     *
91
     * @return string HTML
92
     * @throws Exception
93
     */
94 5
    public function execute($route)
95
    {
96 5
        Inspector::stats('[Router] Executing the request', Inspector::SCOPE_DEBUG);
97
        try {
98
            //Search action and execute
99 5
            return $this->searchAction($route);
100 4
        } catch (AccessDeniedException $e) {
101 2
            Logger::log(t('Solicitamos credenciales de acceso a zona restringida'), LOG_WARNING, ['file' => $e->getFile() . '[' . $e->getLine() . ']']);
102 2
            return Admin::staticAdminLogon();
103 2
        } catch (RouterException $r) {
104 2
            Logger::log($r->getMessage(), LOG_WARNING);
105 2
            $code = $r->getCode();
106
        } catch (Exception $e) {
107
            Logger::log($e->getMessage(), LOG_ERR);
108
            throw $e;
109
        }
110
111 2
        throw new RouterException(t('Página no encontrada'), $code);
112
    }
113
114
    /**
115
     * @param string $route
116
     * @return mixed
117
     * @throws AccessDeniedException
118
     * @throws AdminCredentialsException
119
     * @throws RouterException
120
     * @throws Exception
121
     */
122 5
    protected function searchAction($route)
123
    {
124 5
        Inspector::stats('[Router] Searching action to execute: ' . $route, Inspector::SCOPE_DEBUG);
125
        //Revisamos si tenemos la ruta registrada
126 5
        $parts = parse_url($route);
127 5
        $path = array_key_exists('path', $parts) ? $parts['path'] : $route;
128 5
        $httpRequest = Request::getInstance()->getMethod();
129 5
        foreach ($this->routing as $pattern => $action) {
130 5
            list($httpMethod, $routePattern) = RouterHelper::extractHttpRoute($pattern);
131 5
            $matched = RouterHelper::matchRoutePattern($routePattern, $path);
132 5
            if ($matched && ($httpMethod === 'ALL' || $httpRequest === $httpMethod) && RouterHelper::compareSlashes($routePattern, $path)) {
133
                // Checks restricted access
134 3
                SecurityHelper::checkRestrictedAccess($route);
135 1
                $get = RouterHelper::extractComponents($route, $routePattern);
136
                /** @var $class Controller */
137 1
                $class = RouterHelper::getClassToCall($action);
138
                try {
139 1
                    if ($this->checkRequirements($action, $get)) {
140 1
                        return $this->executeCachedRoute($route, $action, $class, $get);
0 ignored issues
show
Bug introduced by
$class of type PSFS\base\types\Controller is incompatible with the type string expected by parameter $class of PSFS\base\Router::executeCachedRoute(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

140
                        return $this->executeCachedRoute($route, $action, /** @scrutinizer ignore-type */ $class, $get);
Loading history...
141
                    }
142
143
                    throw new RouterException(t('Preconditions failed'), 412);
144
                } catch (Exception $e) {
145
                    Logger::log($e->getMessage(), LOG_ERR);
146
                    throw $e;
147
                }
148
            }
149
        }
150 2
        throw new RouterException(t('Ruta no encontrada'));
151
    }
152
153
    /**
154
     * @param array $action
155
     * @param array $params
156
     * @return bool
157
     */
158 1
    private function checkRequirements(array $action, $params = [])
159
    {
160 1
        Inspector::stats('[Router] Checking request requirements', Inspector::SCOPE_DEBUG);
161 1
        if (!empty($params) && !empty($action['requirements'])) {
162
            $checked = 0;
163
            foreach (array_keys($params) as $key) {
164
                if (in_array($key, $action['requirements'], true) && strlen($params[$key])) {
165
                    $checked++;
166
                }
167
            }
168
            $valid = count($action['requirements']) === $checked;
169
        } else {
170 1
            $valid = true;
171
        }
172 1
        return $valid;
173
    }
174
175
    /**
176
     * @throws ConfigException
177
     * @throws InvalidArgumentException
178
     * @throws ReflectionException
179
     * @throws GeneratorException
180
     */
181 5
    private function generateRouting()
182
    {
183 5
        $base = SOURCE_DIR;
184 5
        $modulesPath = realpath(CORE_DIR);
185 5
        $this->routing = $this->inspectDir($base, 'PSFS', array());
186 5
        $this->checkExternalModules();
187 5
        if (file_exists($modulesPath)) {
188 1
            $modules = $this->finder->directories()->in($modulesPath)->depth(0);
189 1
            if ($modules->hasResults()) {
190 1
                foreach ($modules->getIterator() as $modulePath) {
191 1
                    $module = $modulePath->getBasename();
192 1
                    $this->routing = $this->inspectDir($modulesPath . DIRECTORY_SEPARATOR . $module, $module, $this->routing);
193
                }
194
            }
195
        }
196 5
        $this->cache->storeData(CONFIG_DIR . DIRECTORY_SEPARATOR . 'domains.json', $this->domains, Cache::JSON, TRUE);
197
    }
198
199
    /**
200
     * @throws GeneratorException
201
     * @throws ConfigException
202
     * @throws InvalidArgumentException
203
     * @throws ReflectionException
204
     */
205 5
    public function hydrateRouting()
206
    {
207 5
        $this->generateRouting();
208 5
        $home = Config::getParam('home.action', 'admin');
209 5
        if (NULL !== $home || $home !== '') {
210 5
            $homeParams = NULL;
211 5
            foreach ($this->routing as $pattern => $params) {
212 5
                list($method, $route) = RouterHelper::extractHttpRoute($pattern);
213 5
                if (preg_match('/' . preg_quote($route, '/') . '$/i', '/' . $home)) {
214 5
                    $homeParams = $params;
215
                }
216 5
                unset($method);
217
            }
218 5
            if (NULL !== $homeParams) {
219 5
                $this->routing['/'] = $homeParams;
220
            }
221
        }
222
    }
223
224
    /**
225
     * @param string $namespace
226
     * @return bool
227
     */
228 7
    public static function exists($namespace)
229
    {
230 7
        return (class_exists($namespace) || interface_exists($namespace) || trait_exists($namespace));
231
    }
232
233
    /**
234
     * @param string $slug
235
     * @param boolean $absolute
236
     * @param array $params
237
     *
238
     * @return string|null
239
     * @throws RouterException
240
     */
241 2
    public function getRoute($slug = '', $absolute = false, array $params = [])
242
    {
243 2
        $baseUrl = $absolute ? Request::getInstance()->getRootUrl() : '';
244 2
        if ('' === $slug) {
245 1
            return $baseUrl . '/';
246
        }
247 2
        if (!is_array($this->slugs) || !array_key_exists($slug, $this->slugs)) {
0 ignored issues
show
introduced by
The condition is_array($this->slugs) is always true.
Loading history...
248 1
            throw new RouterException(t('No existe la ruta especificada'));
249
        }
250 2
        $url = $baseUrl . $this->slugs[$slug];
251 2
        if (!empty($params)) {
252
            foreach ($params as $key => $value) {
253
                $url = str_replace('{' . $key . '}', $value, $url);
254
            }
255 2
        } elseif (!empty($this->routing[$this->slugs[$slug]]['default'])) {
256 2
            $url = $baseUrl . $this->routing[$this->slugs[$slug]]['default'];
257
        }
258
259 2
        return preg_replace('/(GET|POST|PUT|DELETE|ALL|HEAD|PATCH)\#\|\#/', '', $url);
260
    }
261
262
    /**
263
     * @param string $class
264
     * @param string $method
265
     */
266 1
    private function checkPreActions($class, $method)
267
    {
268 1
        $preAction = 'pre' . ucfirst($method);
269 1
        if (method_exists($class, $preAction)) {
270
            Inspector::stats('[Router] Pre action invoked', Inspector::SCOPE_DEBUG);
271
            try {
272
                if (false === call_user_func_array([$class, $preAction])) {
0 ignored issues
show
Bug introduced by
The call to call_user_func_array() has too few arguments starting with args. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

272
                if (false === /** @scrutinizer ignore-call */ call_user_func_array([$class, $preAction])) {

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
273
                    Logger::log(t('Pre action failed'), LOG_ERR, [error_get_last()]);
274
                    error_clear_last();
275
                }
276
            } catch (Exception $e) {
277
                Logger::log($e->getMessage(), LOG_ERR, [$class, $method]);
278
            }
279
        }
280
    }
281
282
    /**
283
     * @param string $route
284
     * @param array $action
285
     * @param string $class
286
     * @param array $params
287
     * @return mixed
288
     * @throws GeneratorException
289
     * @throws ConfigException
290
     */
291 1
    protected function executeCachedRoute($route, $action, $class, $params = NULL)
292
    {
293 1
        Inspector::stats('[Router] Executing route ' . $route, Inspector::SCOPE_DEBUG);
294 1
        $action['params'] = array_merge($action['params'], $params, Request::getInstance()->getQueryParams());
0 ignored issues
show
Bug introduced by
It seems like $params can also be of type null; however, parameter $arrays of array_merge() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

294
        $action['params'] = array_merge($action['params'], /** @scrutinizer ignore-type */ $params, Request::getInstance()->getQueryParams());
Loading history...
295 1
        Security::getInstance()->setSessionKey(Cache::CACHE_SESSION_VAR, $action);
296 1
        $cache = Cache::needCache();
297 1
        $execute = TRUE;
298 1
        $return = null;
299 1
        if (FALSE !== $cache && $action['http'] === 'GET' && Config::getParam('debug') === FALSE) {
300
            list($path, $cacheDataName) = $this->cache->getRequestCacheHash();
301
            $cachedData = $this->cache->readFromCache('json' . DIRECTORY_SEPARATOR . $path . $cacheDataName, $cache);
0 ignored issues
show
Bug introduced by
It seems like $cache can also be of type true; however, parameter $expires of PSFS\base\Cache::readFromCache() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

301
            $cachedData = $this->cache->readFromCache('json' . DIRECTORY_SEPARATOR . $path . $cacheDataName, /** @scrutinizer ignore-type */ $cache);
Loading history...
302
            if (NULL !== $cachedData) {
303
                $headers = $this->cache->readFromCache('json' . DIRECTORY_SEPARATOR . $path . $cacheDataName . '.headers', $cache, null, Cache::JSON);
304
                Template::getInstance()->renderCache($cachedData, $headers);
305
                $execute = FALSE;
306
            }
307
        }
308 1
        if ($execute) {
309 1
            Inspector::stats('[Router] Start executing action ' . $route, Inspector::SCOPE_DEBUG);
310 1
            $this->checkPreActions($class, $action['method']);
311 1
            $return = call_user_func_array([$class, $action['method']], $params);
0 ignored issues
show
Bug introduced by
It seems like $params can also be of type null; however, parameter $args of call_user_func_array() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

311
            $return = call_user_func_array([$class, $action['method']], /** @scrutinizer ignore-type */ $params);
Loading history...
312 1
            if (false === $return) {
313
                Logger::log(t('An error occurred trying to execute the action'), LOG_ERR, [error_get_last()]);
314
            }
315
        }
316 1
        return $return;
317
    }
318
319
    /**
320
     * @param Exception|null $exception
321
     * @param bool $isJson
322
     * @return string
323
     * @throws GeneratorException
324
     */
325
    public function httpNotFound(\Exception $exception = null, $isJson = false)
326
    {
327
        return ResponseHelper::httpNotFound($exception, $isJson);
328
    }
329
}
330