Test Failed
Push — master ( f7ffcc...a40e1b )
by Fran
03:18
created

Router::execute()   B

Complexity

Conditions 5
Paths 13

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 17
nc 13
nop 1
dl 0
loc 25
ccs 0
cts 17
cp 0
crap 30
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
namespace PSFS\base;
4
5
use PSFS\base\config\Config;
6
use PSFS\base\exception\AccessDeniedException;
7
use PSFS\base\exception\ConfigException;
8
use PSFS\base\exception\RouterException;
9
use PSFS\base\types\helpers\RequestHelper;
10
use PSFS\base\types\helpers\RouterHelper;
11
use PSFS\base\types\helpers\SecurityHelper;
12
use PSFS\base\types\SingletonTrait;
13
use PSFS\controller\base\Admin;
14
use PSFS\services\AdminServices;
15
use Symfony\Component\Finder\Finder;
16
17
18
/**
19
 * Class Router
20
 * @package PSFS
21
 */
22
class Router
23
{
24
25
    use SingletonTrait;
26
27
    protected $routing;
28
    protected $slugs;
29
    private $domains;
30
    /**
31
     * @var Finder $finder
32
     */
33
    private $finder;
34
    /**
35
     * @var \PSFS\base\Cache $cache
36
     */
37
    private $cache;
38
    /**
39
     * @var bool headersSent
40
     */
41
    protected $headersSent = false;
42
43
    /**
44
     * Constructor Router
45
     * @throws ConfigException
46
     */
47 6
    public function __construct()
48
    {
49 6
        $this->finder = new Finder();
50 6
        $this->cache = Cache::getInstance();
51 6
        $this->init();
52 6
    }
53
54
    /**
55
     * Inicializador Router
56
     * @throws ConfigException
57
     */
58 1
    public function init()
59
    {
60 1
        if (!file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . "urls.json") || Config::getInstance()->getDebugMode()) {
61 1
            $this->hydrateRouting();
62 1
            $this->simpatize();
63 1
        } else {
64 1
            list($this->routing, $this->slugs) = $this->cache->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . "urls.json", Cache::JSON, TRUE);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 146 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
65 1
            $this->domains = $this->cache->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . "domains.json", Cache::JSON, TRUE);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 129 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
66
        }
67 1
    }
68
69
    /**
70
     * Método que deriva un error HTTP de página no encontrada
71
     *
72
     * @param \Exception $e
73
     *
74
     * @return string HTML
75
     */
76
    public function httpNotFound(\Exception $e = NULL)
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...
77
    {
78
        Logger::log('Throw not found exception');
79
        $template = Template::getInstance()->setStatus($e->getCode());
80
        if (preg_match('/json/i', Request::getInstance()->getServer('CONTENT_TYPE'))) {
81
            return $template->output(json_encode(array(
82
                "success" => FALSE,
83
                "error" => $e->getMessage(),
84
            )), 'application/json');
85
        } else {
86
            if (NULL === $e) {
87
                Logger::log('Not found page throwed without previous exception', LOG_WARNING);
88
                $e = new \Exception(_('Page not found'), 404);
89
            }
90
91
            return $template->render('error.html.twig', array(
92
                'exception' => $e,
93
                'trace' => $e->getTraceAsString(),
94
                'error_page' => TRUE,
95
            ));
96
        }
97
    }
98
99
    /**
100
     * Método que devuelve las rutas
101
     * @return string|null
102
     */
103
    public function getSlugs()
104
    {
105
        return $this->slugs;
106
    }
107
108
    /**
109
     * Method that extract all routes in the platform
110
     * @return array
111
     */
112
    public function getAllRoutes() {
113
        $routes = [];
114
        foreach($this->routing as $path => $route) {
115
            if(array_key_exists('slug', $route)) {
116
                $routes[$route['slug']] = $path;
117
            }
118
        }
119
        return $routes;
120
    }
121
122
    /**
123
     * Método que calcula el objeto a enrutar
124
     *
125
     * @param string|null $route
126
     *
127
     * @throws \Exception
128
     * @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...
129
     */
130
    public function execute($route)
131
    {
132
        Logger::log('Executing the request');
133
        try {
134
            //Check CORS for requests
135
            RequestHelper::checkCORS();
136
            // Checks restricted access
137
            SecurityHelper::checkRestrictedAccess($route);
138
            //Search action and execute
139
            $this->searchAction($route);
140
        } catch (AccessDeniedException $e) {
141
            Logger::log(_('Solicitamos credenciales de acceso a zona restringida'));
142
            return Admin::staticAdminLogon($route);
143
        } catch (RouterException $r) {
144
            if(null === RouterHelper::checkDefaultRoute($route)) {
145
                Logger::log($r->getMessage(), LOG_WARNING);
146
                throw $r;
147
            }
148
        } catch (\Exception $e) {
149
            Logger::log($e->getMessage(), LOG_ERR);
150
            throw $e;
151
        }
152
153
        return $this->httpNotFound();
154
    }
155
156
    /**
157
     * Método que busca el componente que ejecuta la ruta
158
     *
159
     * @param string $route
160
     *
161
     * @throws \PSFS\base\exception\RouterException
162
     */
163
    protected function searchAction($route)
164
    {
165
        Logger::log('Searching action to execute: ' . $route, LOG_INFO);
166
        //Revisamos si tenemos la ruta registrada
167
        $parts = parse_url($route);
168
        $path = (array_key_exists('path', $parts)) ? $parts['path'] : $route;
169
        $httpRequest = Request::getInstance()->getMethod();
170
        foreach ($this->routing as $pattern => $action) {
171
            list($httpMethod, $routePattern) = RouterHelper::extractHttpRoute($pattern);
172
            $matched = RouterHelper::matchRoutePattern($routePattern, $path);
173
            if ($matched && ($httpMethod === "ALL" || $httpRequest === $httpMethod) && RouterHelper::compareSlashes($routePattern, $path)) {
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 140 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
174
                $get = RouterHelper::extractComponents($route, $routePattern);
175
                /** @var $class \PSFS\base\types\Controller */
176
                $class = RouterHelper::getClassToCall($action);
177
                try {
178
                    $this->executeCachedRoute($route, $action, $class, $get);
179
                } catch (\Exception $e) {
180
                    Logger::log($e->getMessage(), LOG_ERR);
181
                    throw new RouterException($e->getMessage(), 404, $e);
182
                }
183
            }
184
        }
185
        throw new RouterException(_("Ruta no encontrada"));
186
    }
187
188
    /**
189
     * Método que manda las cabeceras de autenticación
190
     * @return string HTML
191
     */
192
    protected function sentAuthHeader()
193
    {
194
        return AdminServices::getInstance()->setAdminHeaders();
195
    }
196
197
    /**
198
     * Method that gather all the routes in the project
199
     */
200
    private function generateRouting()
201
    {
202
        $base = SOURCE_DIR;
203
        $modules = realpath(CORE_DIR);
204
        $this->routing = $this->inspectDir($base, "PSFS", array());
205
        if (file_exists($modules)) {
206
            $module = "";
207 1
            if(file_exists($modules . DIRECTORY_SEPARATOR . 'module.json')) {
208
                $mod_cfg = json_decode(file_get_contents($modules . DIRECTORY_SEPARATOR . 'module.json'), true);
209 1
                $module = $mod_cfg['module'];
210 1
            }
211 1
            $this->routing = $this->inspectDir($modules, $module, $this->routing);
212 1
        }
213
        $this->cache->storeData(CONFIG_DIR . DIRECTORY_SEPARATOR . "domains.json", $this->domains, Cache::JSON, TRUE);
214
    }
215
216
    /**
217
     * Método que regenera el fichero de rutas
218
     * @throws ConfigException
219
     */
220 1
    public function hydrateRouting()
221 1
    {
222
        $this->generateRouting();
223
        $home = Config::getInstance()->get('home_action');
224
        if (NULL !== $home || $home !== '') {
225
            $home_params = NULL;
226
            foreach ($this->routing as $pattern => $params) {
227 1
                list($method, $route) = RouterHelper::extractHttpRoute($pattern);
228
                if (preg_match("/" . preg_quote($route, "/") . "$/i", "/" . $home)) {
229 1
                    $home_params = $params;
230 1
                }
231 1
            }
232 1
            if (NULL !== $home_params) {
233 1
                $this->routing['/'] = $home_params;
234 1
            }
235 1
        }
236
    }
237
238 1
    /**
239 1
     * Método que inspecciona los directorios en busca de clases que registren rutas
240
     *
241
     * @param string $origen
242 1
     * @param string $namespace
243 1
     * @param array $routing
244
     *
245
     * @return array
246
     * @throws ConfigException
247
     */
248
    private function inspectDir($origen, $namespace = 'PSFS', $routing)
249
    {
250
        $files = $this->finder->files()->in($origen)->path('/(controller|api)/i')->name("*.php");
251
        foreach ($files as $file) {
252
            $filename = str_replace("/", '\\', str_replace($origen, '', $file->getPathname()));
253
            $routing = $this->addRouting($namespace . str_replace('.php', '', $filename), $routing);
254
        }
255 1
        $this->finder = new Finder();
256
257 1
        return $routing;
258 1
    }
259 1
260 1
    /**
261 1
     * Checks that a namespace exists
262 1
     * @param string $namespace
263
     * @return bool
264 1
     */
265
    public static function exists($namespace) {
266
        return (class_exists($namespace) || interface_exists($namespace) || trait_exists($namespace));
267
    }
268
269
    /**
270
     * Método que añade nuevas rutas al array de referencia
271
     *
272 1
     * @param string $namespace
273 1
     * @param array $routing
274
     *
275
     * @return array
276
     * @throws ConfigException
277
     */
278
    private function addRouting($namespace, &$routing)
279
    {
280
        if (self::exists($namespace)) {
281
            $reflection = new \ReflectionClass($namespace);
282
            if (FALSE === $reflection->isAbstract() && FALSE === $reflection->isInterface()) {
283
                $this->extractDomain($reflection);
284
                $classComments = $reflection->getDocComment();
285 1
                preg_match('/@api\ (.*)\n/im', $classComments, $apiPath);
286
                $api = '';
287 1
                if (count($apiPath)) {
288 1
                    $api = array_key_exists(1, $apiPath) ? $apiPath[1] : $api;
289 1
                }
290 1
                foreach ($reflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
291 1
                    list($route, $info) = RouterHelper::extractRouteInfo($method, $api);
292 1
                    if(null !== $route && null !== $info) {
293 1
                        $info['class'] = $namespace;
294 1
                        $routing[$route] = $info;
295
                    }
296
                }
297 1
            }
298 1
        }
299 1
300 1
        return $routing;
301 1
    }
302 1
303 1
    /**
304 1
     * Método que extrae de la ReflectionClass los datos necesarios para componer los dominios en los templates
305 1
     *
306
     * @param \ReflectionClass $class
307 1
     *
308
     * @return Router
309
     * @throws ConfigException
310
     */
311
    protected function extractDomain(\ReflectionClass $class)
312
    {
313
        //Calculamos los dominios para las plantillas
314
        if ($class->hasConstant("DOMAIN")) {
315
            $domain = "@" . $class->getConstant("DOMAIN") . "/";
316
            $this->domains[$domain] = RouterHelper::extractDomainInfo($class, $domain);
317
        }
318 1
319
        return $this;
320
    }
321 1
322 1
    /**
323 1
     * Método que genera las urls amigables para usar dentro del framework
324 1
     * @return Router
325
     */
326 1
    public function simpatize()
327
    {
328
        $translationFileName = "translations" . DIRECTORY_SEPARATOR . "routes_translations.php";
329
        $absoluteTranslationFileName = CACHE_DIR . DIRECTORY_SEPARATOR . $translationFileName;
330
        $this->generateSlugs($absoluteTranslationFileName);
331
        Config::createDir(CONFIG_DIR);
332
        Cache::getInstance()->storeData(CONFIG_DIR . DIRECTORY_SEPARATOR . "urls.json", array($this->routing, $this->slugs), Cache::JSON, TRUE);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 144 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
333 1
334
        return $this;
335 1
    }
336 1
337 1
    /**
338 1
     * Método que devuelve el slug de un string dado
339 1
     *
340
     * @param string $text
341 1
     *
342
     * @return string
343
     */
344
    private function slugify($text)
345
    {
346
        // replace non letter or digits by -
347
        $text = preg_replace('~[^\\pL\d]+~u', '-', $text);
348
349
        // trim
350
        $text = trim($text, '-');
351 1
352
        // transliterate
353
        if (function_exists('iconv')) {
354 1
            $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
355
        }
356
357 1
        // lowercase
358
        $text = strtolower($text);
359
360 1
        // remove unwanted characters
361 1
        $text = preg_replace('~[^-\w]+~', '', $text);
362 1
363
        if (empty($text)) {
364
            return 'n-a';
365 1
        }
366
367
        return $text;
368 1
    }
369
370 1
    /**
371
     * Método que devuelve una ruta del framework
372
     *
373
     * @param string $slug
374 1
     * @param boolean $absolute
375
     * @param array $params
376
     *
377
     * @return string|null
378
     * @throws RouterException
379
     */
380
    public function getRoute($slug = '', $absolute = FALSE, $params = [])
381
    {
382
        if (strlen($slug) === 0) {
383
            return ($absolute) ? Request::getInstance()->getRootUrl() . '/' : '/';
384
        }
385
        if (NULL === $slug || !array_key_exists($slug, $this->slugs)) {
386
            throw new RouterException(_("No existe la ruta especificada"));
387
        }
388
        $url = ($absolute) ? Request::getInstance()->getRootUrl() . $this->slugs[$slug] : $this->slugs[$slug];
389
        if (!empty($params)) foreach ($params as $key => $value) {
390
            $url = str_replace("{" . $key . "}", $value, $url);
391
        } elseif (!empty($this->routing[$this->slugs[$slug]]["default"])) {
392
            $url = ($absolute) ? Request::getInstance()->getRootUrl() . $this->routing[$this->slugs[$slug]]["default"] : $this->routing[$this->slugs[$slug]]["default"];
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 168 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
393
        }
394
395
        return preg_replace('/(GET|POST|PUT|DELETE|ALL)\#\|\#/', '', $url);
396
    }
397
398
    /**
399
     * Método que devuelve las rutas de administración
400
     * @return array
401
     */
402
    public function getAdminRoutes()
403
    {
404
        $routes = array();
405
        foreach ($this->routing as $route => $params) {
406
            list($httpMethod, $routePattern) = RouterHelper::extractHttpRoute($route);
407
            if (preg_match('/^\/admin(\/|$)/', $routePattern)) {
408
                if (preg_match('/^\\\?PSFS/', $params["class"])) {
409 1
                    $profile = "superadmin";
410
                } else {
411 1
                    $profile = "admin";
412 1
                }
413 1
                if (!empty($params["default"]) && preg_match('/(GET|ALL)/i', $httpMethod)) {
414 1
                    $_profile = ($params["visible"]) ? $profile : 'adminhidden';
415 1
                    if (!array_key_exists($_profile, $routes)) {
416 1
                        $routes[$_profile] = array();
417 1
                    }
418
                    $routes[$_profile][] = $params["slug"];
419
                }
420 1
            }
421 1
        }
422 1
        if (array_key_exists("superadmin", $routes)) {
423 1
            asort($routes["superadmin"]);
424 1
        }
425 1
        if (array_key_exists("adminhidden", $routes)) {
426 1
            asort($routes["adminhidden"]);
427 1
        }
428 1
        if (array_key_exists('admin', $routes)) {
429 1
            asort($routes["admin"]);
430 1
        }
431 1
        return $routes;
432 1
    }
433 1
434 1
    /**
435 1
     * Método que devuelve le controlador del admin
436
     * @return Admin
437
     */
438 1
    public function getAdmin()
439
    {
440
        return Admin::getInstance();
441
    }
442
443
    /**
444
     * Método que extrae los dominios
445
     * @return array
446
     */
447
    public function getDomains()
448
    {
449
        return $this->domains ?: [];
450
    }
451
452
    /**
453
     * Método que ejecuta una acción del framework y revisa si lo tenemos cacheado ya o no
454
     *
455
     * @param string $route
456
     * @param array|null $action
457
     * @param types\Controller $class
458
     * @param array $params
0 ignored issues
show
Documentation introduced by
Should the type for parameter $params not be array|null? Also, consider making the array more specific, something like array<String>, or String[].

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive. In addition it looks for parameters that have the generic type array and suggests a stricter type like array<String>.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
459
     */
460
    protected function executeCachedRoute($route, $action, $class, $params = NULL)
461
    {
462
        Logger::log('Executing route ' . $route, LOG_INFO);
463
        Security::getInstance()->setSessionKey("__CACHE__", $action);
464
        $cache = Cache::needCache();
465
        $execute = TRUE;
466
        if (FALSE !== $cache && Config::getInstance()->getDebugMode() === FALSE) {
467
            $cacheDataName = $this->cache->getRequestCacheHash();
468
            $cachedData = $this->cache->readFromCache("templates" . DIRECTORY_SEPARATOR . $cacheDataName,
469
                $cache, function () {});
0 ignored issues
show
Bug introduced by
It seems like $cache defined by \PSFS\base\Cache::needCache() on line 464 can also be of type boolean; however, PSFS\base\Cache::readFromCache() does only seem to accept integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
470
            if (NULL !== $cachedData) {
471
                $headers = $this->cache->readFromCache("templates" . DIRECTORY_SEPARATOR . $cacheDataName . ".headers",
472
                    $cache, function () {}, Cache::JSON);
0 ignored issues
show
Bug introduced by
It seems like $cache defined by \PSFS\base\Cache::needCache() on line 464 can also be of type boolean; however, PSFS\base\Cache::readFromCache() does only seem to accept integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
473
                Template::getInstance()->renderCache($cachedData, $headers);
474
                $execute = FALSE;
475
            }
476
        }
477
        if ($execute) {
478
            call_user_func_array(array($class, $action['method']), $params);
479
        }
480
    }
481
482
    /**
483
     * Parse slugs to create translations
484
     *
485
     * @param string $absoluteTranslationFileName
486
     */
487
    private function generateSlugs($absoluteTranslationFileName)
488
    {
489
        $translations = $this->generateTranslationsFile($absoluteTranslationFileName);
490
        foreach ($this->routing as $key => &$info) {
491
            $keyParts = $key;
492
            if (FALSE === strstr("#|#", $key)) {
493
                $keyParts = explode("#|#", $key);
494 1
                $keyParts = array_key_exists(1, $keyParts) ? $keyParts[1] : '';
495
            }
496 1
            $slug = $this->slugify($keyParts);
497 1
            if (NULL !== $slug && !array_key_exists($slug, $translations)) {
498 1
                $translations[$slug] = $key;
499 1
                file_put_contents($absoluteTranslationFileName, "\$translations[\"{$slug}\"] = _(\"{$slug}\");\n", FILE_APPEND);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 128 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
500 1
            }
501 1
            $this->slugs[$slug] = $key;
502 1
            $info["slug"] = $slug;
503 1
        }
504 1
    }
505 1
506 1
    /**
507 1
     * Create translation file if not exists
508 1
     *
509 1
     * @param string $absoluteTranslationFileName
510 1
     *
511 1
     * @return array
512
     */
513
    private function generateTranslationsFile($absoluteTranslationFileName)
514
    {
515
        $translations = array();
516
        if (file_exists($absoluteTranslationFileName)) {
517
            include($absoluteTranslationFileName);
518
        } else {
519
            Cache::getInstance()->storeData($absoluteTranslationFileName, "<?php \$translations = array();\n", Cache::TEXT, TRUE);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 130 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
520 1
        }
521
522 1
        return $translations;
523 1
    }
524
525
}
526