Passed
Push — master ( 790feb...d12e0f )
by Fran
02:56
created

Router::generateRouting()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 11
c 0
b 0
f 0
nc 3
nop 0
dl 0
loc 16
ccs 12
cts 12
cp 1
crap 4
rs 9.9
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 4
    }
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 5
    }
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 5
    }
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 5
        $code = 404;
0 ignored issues
show
Unused Code introduced by
The assignment to $code is dead and can be removed.
Loading history...
98
        try {
99
            //Search action and execute
100 5
            return $this->searchAction($route);
101 4
        } catch (AccessDeniedException $e) {
102 1
            Logger::log(t('Solicitamos credenciales de acceso a zona restringida'), LOG_WARNING, ['file' => $e->getFile() . '[' . $e->getLine() . ']']);
103 1
            return Admin::staticAdminLogon();
104 3
        } catch (RouterException $r) {
105 3
            Logger::log($r->getMessage(), LOG_WARNING);
106 3
            $code = $r->getCode();
107
        } catch (Exception $e) {
108
            Logger::log($e->getMessage(), LOG_ERR);
109
            throw $e;
110
        }
111
112 3
        throw new RouterException(t('Página no encontrada'), $code);
113
    }
114
115
    /**
116
     * @param string $route
117
     * @return mixed
118
     * @throws AccessDeniedException
119
     * @throws AdminCredentialsException
120
     * @throws RouterException
121
     * @throws Exception
122
     */
123 5
    protected function searchAction($route)
124
    {
125 5
        Inspector::stats('[Router] Searching action to execute: ' . $route, Inspector::SCOPE_DEBUG);
126
        //Revisamos si tenemos la ruta registrada
127 5
        $parts = parse_url($route);
128 5
        $path = array_key_exists('path', $parts) ? $parts['path'] : $route;
129 5
        $httpRequest = Request::getInstance()->getMethod();
130 5
        foreach ($this->routing as $pattern => $action) {
131 5
            list($httpMethod, $routePattern) = RouterHelper::extractHttpRoute($pattern);
132 5
            $matched = RouterHelper::matchRoutePattern($routePattern, $path);
133 5
            if ($matched && ($httpMethod === 'ALL' || $httpRequest === $httpMethod) && RouterHelper::compareSlashes($routePattern, $path)) {
134
                // Checks restricted access
135 4
                SecurityHelper::checkRestrictedAccess($route);
136 3
                $get = RouterHelper::extractComponents($route, $routePattern);
137
                /** @var $class Controller */
138 3
                $class = RouterHelper::getClassToCall($action);
139
                try {
140 3
                    if ($this->checkRequirements($action, $get)) {
141 2
                        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

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

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

273
                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...
274
                    Logger::log(t('Pre action failed'), LOG_ERR, [error_get_last()]);
275
                    error_clear_last();
276
                }
277
            } catch (Exception $e) {
278
                Logger::log($e->getMessage(), LOG_ERR, [$class, $method]);
279
            }
280
        }
281 2
    }
282
283
    /**
284
     * @param string $route
285
     * @param array $action
286
     * @param string $class
287
     * @param array $params
288
     * @return mixed
289
     * @throws GeneratorException
290
     * @throws ConfigException
291
     */
292 2
    protected function executeCachedRoute($route, $action, $class, $params = NULL)
293
    {
294 2
        Inspector::stats('[Router] Executing route ' . $route, Inspector::SCOPE_DEBUG);
295 2
        $action['params'] = array_merge($action['params'], $params, Request::getInstance()->getQueryParams());
296 2
        Security::getInstance()->setSessionKey(Cache::CACHE_SESSION_VAR, $action);
297 2
        $cache = Cache::needCache();
298 2
        $execute = TRUE;
299 2
        $return = null;
300 2
        if (FALSE !== $cache && $action['http'] === 'GET' && Config::getParam('debug') === FALSE) {
301
            list($path, $cacheDataName) = $this->cache->getRequestCacheHash();
302
            $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

302
            $cachedData = $this->cache->readFromCache('json' . DIRECTORY_SEPARATOR . $path . $cacheDataName, /** @scrutinizer ignore-type */ $cache);
Loading history...
303
            if (NULL !== $cachedData) {
304
                $headers = $this->cache->readFromCache('json' . DIRECTORY_SEPARATOR . $path . $cacheDataName . '.headers', $cache, null, Cache::JSON);
305
                Template::getInstance()->renderCache($cachedData, $headers);
306
                $execute = FALSE;
307
            }
308
        }
309 2
        if ($execute) {
310 2
            Inspector::stats('[Router] Start executing action ' . $route, Inspector::SCOPE_DEBUG);
311 2
            $this->checkPreActions($class, $action['method']);
312 2
            $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 $param_arr 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

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