Test Failed
Push — master ( 0d14a6...e876c1 )
by Fran
09:15
created

Router::execute()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5.1576

Importance

Changes 0
Metric Value
cc 4
eloc 13
nc 4
nop 1
dl 0
loc 18
ccs 7
cts 12
cp 0.5833
crap 5.1576
rs 9.2
c 0
b 0
f 0
1
<?php
2
namespace PSFS\base;
3
4
use PSFS\base\config\Config;
5
use PSFS\base\dto\JsonResponse;
6
use PSFS\base\exception\AccessDeniedException;
7
use PSFS\base\exception\ConfigException;
8
use PSFS\base\exception\RouterException;
9
use PSFS\base\types\helpers\AdminHelper;
10
use PSFS\base\types\helpers\GeneratorHelper;
11
use PSFS\base\types\helpers\I18nHelper;
12
use PSFS\base\types\helpers\RequestHelper;
13
use PSFS\base\types\helpers\RouterHelper;
14
use PSFS\base\types\helpers\SecurityHelper;
15
use PSFS\base\types\traits\SingletonTrait;
16
use PSFS\controller\base\Admin;
17
use PSFS\services\AdminServices;
18
use Symfony\Component\Finder\Finder;
19
20
21
/**
22
 * Class Router
23
 * @package PSFS
24
 */
25
class Router
26
{
27
    use SingletonTrait;
28
29
    protected $routing;
30
    protected $slugs;
31
    private $domains = [];
32
    /**
33
     * @var Finder $finder
34
     */
35
    private $finder;
36
    /**
37
     * @var \PSFS\base\Cache $cache
38
     */
39
    private $cache;
40
    /**
41
     * @var bool headersSent
42
     */
43
    protected $headersSent = false;
44
    /**
45
     * @var int
46
     */
47
    protected $cacheType = Cache::JSON;
48
    /**
49
     * @var bool
50
     */
51
    protected $loaded = false;
52 1
53
    /**
54 1
     * Constructor Router
55 1
     * @throws ConfigException
56 1
     */
57 1
    public function __construct()
58
    {
59
        $this->finder = new Finder();
60
        $this->cache = Cache::getInstance();
61
        $this->init();
62
    }
63 1
64
    /**
65 1
     * Inicializador Router
66 1
     * @throws ConfigException
67 1
     */
68 1
    public function init()
69
    {
70 1
        list($this->routing, $this->slugs) = $this->cache->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . "urls.json", $this->cacheType, TRUE);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 147 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...
71 1
        if (empty($this->routing) || Config::getInstance()->getDebugMode()) {
72
            $this->debugLoad();
73
        } else {
74
            $this->domains = $this->cache->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . "domains.json", $this->cacheType, TRUE);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 134 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...
75
        }
76 1
        $this->checkExternalModules(false);
77 1
        $this->setLoaded(true);
78 1
    }
79 1
80 1
    /**
81 1
     * Load routes and domains and store them
82
     */
83
    private function debugLoad() {
84
        Logger::log('Begin routes load', LOG_DEBUG);
85
        $this->hydrateRouting();
86
        $this->simpatize();
87
        Logger::log('End routes load', LOG_DEBUG);
88
    }
89
90
    /**
91
     * Método que deriva un error HTTP de página no encontrada
92
     *
93
     * @param \Exception $e
0 ignored issues
show
Documentation introduced by
Should the type for parameter $e not be null|\Exception?

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.

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

Loading history...
94
     * @param boolean $isJson
95
     *
96
     * @return string HTML
97
     */
98
    public function httpNotFound(\Exception $e = NULL, $isJson = false)
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...
99
    {
100
        Logger::log('Throw not found exception');
101
        if (NULL === $e) {
102
            Logger::log('Not found page throwed without previous exception', LOG_WARNING);
103
            $e = new \Exception(_('Page not found'), 404);
104
        }
105
        $template = Template::getInstance()->setStatus($e->getCode());
106
        if (preg_match('/json/i', Request::getInstance()->getServer('CONTENT_TYPE')) || $isJson) {
107
            $response = new JsonResponse(null, false, 0, 0, $e->getMessage());
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
108
            return $template->output(json_encode($response), 'application/json');
109
        } else {
110
            $not_found_rouote = Config::getParam('route.404');
111
            if(null !== $not_found_rouote) {
112
                Request::getInstance()->redirect($this->getRoute($not_found_rouote, true));
113
            } else {
114
                return $template->render('error.html.twig', array(
115
                    'exception' => $e,
116
                    'trace' => $e->getTraceAsString(),
117
                    'error_page' => TRUE,
118
                ));
119
            }
120
        }
121
    }
122 1
123
    /**
124 1
     * Método que devuelve las rutas
125
     * @return string|null
126
     */
127
    public function getSlugs()
128
    {
129
        return $this->slugs;
130 2
    }
131 2
132
    /**
133
     * @return mixed
134
     */
135
    public function getRoutes() {
136
        return $this->routing;
137
    }
138 1
139
    /**
140 1
     * Method that extract all routes in the platform
141 1
     * @return array
142 1
     */
143 1
    public function getAllRoutes()
144
    {
145
        $routes = [];
146 1
        foreach ($this->getRoutes() as $path => $route) {
147
            if (array_key_exists('slug', $route)) {
148
                $routes[$route['slug']] = $path;
149
            }
150
        }
151
        return $routes;
152
    }
153
154
    /**
155
     * Método que calcula el objeto a enrutar
156
     *
157 1
     * @param string|null $route
158
     *
159 1
     * @throws \Exception
160
     * @return string HTML
161
     */
162 1
    public function execute($route)
163
    {
164 1
        Logger::log('Executing the request');
165
        try {
166 1
            //Search action and execute
167 1
            $this->searchAction($route);
168
        } catch (AccessDeniedException $e) {
169
            Logger::log(_('Solicitamos credenciales de acceso a zona restringida'));
170 1
            return Admin::staticAdminLogon($route);
171 1
        } catch (RouterException $r) {
172
            Logger::log($r->getMessage(), LOG_WARNING);
173
        } catch (\Exception $e) {
174
            Logger::log($e->getMessage(), LOG_ERR);
175
            throw $e;
176
        }
177 1
178
        throw new RouterException(_("Página no encontrada"), 404);
179
    }
180
181
    /**
182
     * Método que busca el componente que ejecuta la ruta
183
     *
184
     * @param string $route
185
     *
186
     * @throws \PSFS\base\exception\RouterException
187 1
     */
188
    protected function searchAction($route)
189 1
    {
190
        Logger::log('Searching action to execute: ' . $route, LOG_INFO);
191 1
        //Revisamos si tenemos la ruta registrada
192 1
        $parts = parse_url($route);
193 1
        $path = (array_key_exists('path', $parts)) ? $parts['path'] : $route;
194 1
        $httpRequest = Request::getInstance()->getMethod();
195 1
        foreach ($this->routing as $pattern => $action) {
196 1
            list($httpMethod, $routePattern) = RouterHelper::extractHttpRoute($pattern);
197 1
            $matched = RouterHelper::matchRoutePattern($routePattern, $path);
198
            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...
199
                // Checks restricted access
200
                SecurityHelper::checkRestrictedAccess($route);
201
                $get = RouterHelper::extractComponents($route, $routePattern);
202
                /** @var $class \PSFS\base\types\Controller */
203
                $class = RouterHelper::getClassToCall($action);
204
                try {
205
                    if($this->checkRequirements($action, $get)) {
206
                        $this->executeCachedRoute($route, $action, $class, $get);
207
                    } else {
208
                        throw new RouterException(_('La ruta no es válida'), 400);
209 1
                    }
210
                } catch (\Exception $e) {
211
                    Logger::log($e->getMessage(), LOG_ERR);
212
                    throw new \RuntimeException($e->getMessage(), 404, $e);
213
                }
214
            }
215
        }
216
        throw new RouterException(_("Ruta no encontrada"));
217
    }
218
219
    /**
220
     * @param array $action
221
     * @param array $params
222
     * @return bool
223
     */
224 1
    private function checkRequirements(array $action, array $params = []) {
225 1
        $valid = true;
226 1
        if(!empty($action['requirements'])) {
227
            if(!empty($params)) {
228
                $checked = 0;
229 1
                foreach(array_keys($params) as $key) {
230
                    if(in_array($key, $action['requirements'])) {
231
                        $checked++;
232
                    }
233
                }
234
                $valid = count($action['requirements']) == $checked;
235
            } else {
236 1
                $valid = false;
237
            }
238 1
        }
239 1
        return $valid;
240
    }
241
242
    /**
243
     * Método que manda las cabeceras de autenticación
244
     * @return string HTML
245
     */
246
    protected function sentAuthHeader()
247
    {
248
        return AdminServices::getInstance()->setAdminHeaders();
249
    }
250
251
    /**
252
     * @return string|null
253
     */
254
    private function getExternalModules() {
255
        $externalModules = Config::getParam('modules.extend', '');
256
        if(Config::getParam('psfs.auth', false)) {
257
            $externalModules .= ',psfs/auth';
258
        }
259
        return $externalModules;
260
    }
261 1
262
    /**
263
     * Method that check if the proyect has sub project to include
264
     * @param boolean $hydrateRoute
265
     */
266 1
    private function checkExternalModules($hydrateRoute = true)
267
    {
268 1
        $externalModules = $this->getExternalModules();
269 1
        if (strlen($externalModules)) {
270 1
            $externalModules = explode(',', $externalModules);
271 1
            foreach ($externalModules as &$module) {
272 1
                $module = preg_replace('/(\\\|\/)/', DIRECTORY_SEPARATOR, $module);
273
                $externalModulePath = VENDOR_DIR . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . 'src';
274
                if (file_exists($externalModulePath)) {
275
                    $externalModule = $this->finder->directories()->in($externalModulePath)->depth(0);
276
                    if (!empty($externalModule)) {
277
                        foreach ($externalModule as $modulePath) {
278
                            $extModule = $modulePath->getBasename();
279 1
                            $moduleAutoloader = realpath($externalModulePath . DIRECTORY_SEPARATOR . $extModule . DIRECTORY_SEPARATOR . 'autoload.php');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 152 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...
280 1
                            if (file_exists($moduleAutoloader)) {
281
                                @include $moduleAutoloader;
282
                                if ($hydrateRoute) {
283
                                    $this->routing = $this->inspectDir($externalModulePath . DIRECTORY_SEPARATOR . $extModule, '\\' . $extModule, $this->routing);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 162 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...
284
                                }
285
                            }
286 1
                        }
287
                    }
288 1
                }
289 1
            }
290 1
        }
291 1
    }
292 1
293 1
    /**
294 1
     * Method that gather all the routes in the project
295
     */
296
    private function generateRouting()
297
    {
298 1
        $base = SOURCE_DIR;
299
        $modulesPath = realpath(CORE_DIR);
300
        $this->routing = $this->inspectDir($base, "PSFS", array());
301
        $this->checkExternalModules();
302 1
        if (file_exists($modulesPath)) {
303
            $modules = $this->finder->directories()->in($modulesPath)->depth(0);
304
            foreach ($modules as $modulePath) {
305
                $module = $modulePath->getBasename();
306
                $this->routing = $this->inspectDir($modulesPath . DIRECTORY_SEPARATOR . $module, $module, $this->routing);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 122 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...
307
            }
308
        }
309
        $this->cache->storeData(CONFIG_DIR . DIRECTORY_SEPARATOR . "domains.json", $this->domains, Cache::JSON, TRUE);
310
    }
311
312
    /**
313
     * Método que regenera el fichero de rutas
314 1
     * @throws ConfigException
315
     */
316 1
    public function hydrateRouting()
317 1
    {
318 1
        $this->generateRouting();
319 1
        $home = Config::getInstance()->get('home.action');
320
        if (NULL !== $home || $home !== '') {
321 1
            $home_params = NULL;
322
            foreach ($this->routing as $pattern => $params) {
323 1
                list($method, $route) = RouterHelper::extractHttpRoute($pattern);
324
                if (preg_match("/" . preg_quote($route, "/") . "$/i", "/" . $home)) {
325
                    $home_params = $params;
326
                }
327
            }
328
            if (NULL !== $home_params) {
329
                $this->routing['/'] = $home_params;
330
            }
331 1
        }
332
    }
333 1
334
    /**
335
     * Método que inspecciona los directorios en busca de clases que registren rutas
336
     *
337
     * @param string $origen
338
     * @param string $namespace
339
     * @param array $routing
340
     *
341
     * @return array
342
     * @throws ConfigException
343
     */
344
    private function inspectDir($origen, $namespace = 'PSFS', $routing = [])
345
    {
346 1
        $files = $this->finder->files()->in($origen)->path('/(controller|api)/i')->depth(1)->name("*.php");
347
        foreach ($files as $file) {
348 1
            $filename = str_replace("/", '\\', str_replace($origen, '', $file->getPathname()));
349 1
            $routing = $this->addRouting($namespace . str_replace('.php', '', $filename), $routing, $namespace);
350 1
        }
351 1
        $this->finder = new Finder();
352 1
353 1
        return $routing;
354 1
    }
355 1
356
    /**
357
     * Checks that a namespace exists
358 1
     * @param string $namespace
359 1
     * @return bool
360 1
     */
361
    public static function exists($namespace)
362 1
    {
363 1
        return (class_exists($namespace) || interface_exists($namespace) || trait_exists($namespace));
364 1
    }
365
366
    /**
367
     * Método que añade nuevas rutas al array de referencia
368
     *
369
     * @param string $namespace
370
     * @param array $routing
371 1
     * @param string $module
372
     *
373
     * @return array
374
     * @throws ConfigException
375
     */
376
    private function addRouting($namespace, &$routing, $module = 'PSFS')
377
    {
378
        if (self::exists($namespace)) {
379
            $reflection = new \ReflectionClass($namespace);
380
            if (FALSE === $reflection->isAbstract() && FALSE === $reflection->isInterface()) {
381
                $this->extractDomain($reflection);
382 1
                $classComments = $reflection->getDocComment();
383
                preg_match('/@api\ (.*)\n/im', $classComments, $apiPath);
384
                $api = '';
385 1
                if (count($apiPath)) {
386 1
                    $api = array_key_exists(1, $apiPath) ? $apiPath[1] : $api;
387 1
                }
388
                foreach ($reflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
389 1
                    if (preg_match('/@route\ /i', $method->getDocComment())) {
390 1
                        list($route, $info) = RouterHelper::extractRouteInfo($method, str_replace('\\', '', $api), str_replace('\\', '', $module));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 147 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...
391 1
392
                        if (null !== $route && null !== $info) {
393
                            $info['class'] = $namespace;
394
                            $routing[$route] = $info;
395 1
                        }
396
                    }
397
                }
398
            }
399
        }
400
401
        return $routing;
402 1
    }
403
404 1
    /**
405 1
     * Método que extrae de la ReflectionClass los datos necesarios para componer los dominios en los templates
406 1
     *
407 1
     * @param \ReflectionClass $class
408 1
     *
409
     * @return Router
410 1
     * @throws ConfigException
411
     */
412
    protected function extractDomain(\ReflectionClass $class)
413
    {
414
        //Calculamos los dominios para las plantillas
415
        if ($class->hasConstant("DOMAIN") && !$class->isAbstract()) {
416
            if (!$this->domains) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->domains of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
417
                $this->domains = [];
418
            }
419
            $domain = "@" . $class->getConstant("DOMAIN") . "/";
420
            if (!array_key_exists($domain, $this->domains)) {
421
                $this->domains[$domain] = RouterHelper::extractDomainInfo($class, $domain);
422
            }
423 1
        }
424
425 1
        return $this;
426
    }
427
428 1
    /**
429
     * Método que genera las urls amigables para usar dentro del framework
430
     * @return Router
431 1
     */
432 1
    public function simpatize()
433
    {
434 1
        $translationFileName = "translations" . DIRECTORY_SEPARATOR . "routes_translations.php";
435 1
        $absoluteTranslationFileName = CACHE_DIR . DIRECTORY_SEPARATOR . $translationFileName;
436
        $this->generateSlugs($absoluteTranslationFileName);
437
        GeneratorHelper::createDir(CONFIG_DIR);
438 1
        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...
439
440
        return $this;
441
    }
442
443
    /**
444
     * Método que devuelve una ruta del framework
445
     *
446
     * @param string $slug
447
     * @param boolean $absolute
448
     * @param array $params
449
     *
450
     * @return string|null
451
     * @throws RouterException
452
     */
453
    public function getRoute($slug = '', $absolute = FALSE, $params = [])
454
    {
455
        if (strlen($slug) === 0) {
456
            return ($absolute) ? Request::getInstance()->getRootUrl() . '/' : '/';
457
        }
458
        if (!is_array($this->slugs) || !array_key_exists($slug, $this->slugs)) {
459
            throw new RouterException(_("No existe la ruta especificada"));
460
        }
461
        $url = ($absolute) ? Request::getInstance()->getRootUrl() . $this->slugs[$slug] : $this->slugs[$slug];
462
        if (!empty($params)) foreach ($params as $key => $value) {
463
            $url = str_replace("{" . $key . "}", $value, $url);
464
        } elseif (!empty($this->routing[$this->slugs[$slug]]["default"])) {
465 1
            $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...
466
        }
467 1
468
        return preg_replace('/(GET|POST|PUT|DELETE|ALL)\#\|\#/', '', $url);
469
    }
470
471
    /**
472
     * Método que devuelve las rutas de administración
473
     * @deprecated
474
     * @return array
475
     */
476
    public function getAdminRoutes()
477
    {
478
        return AdminHelper::getAdminRoutes($this->routing);
479
    }
480
481
    /**
482
     * Método que devuelve le controlador del admin
483
     * @deprecated
484
     * @return Admin
485
     */
486
    public function getAdmin()
487
    {
488
        return Admin::getInstance();
489
    }
490
491
    /**
492
     * Método que extrae los dominios
493
     * @return array
494
     */
495
    public function getDomains()
496
    {
497
        return $this->domains ?: [];
498
    }
499
500
    /**
501
     * Método que ejecuta una acción del framework y revisa si lo tenemos cacheado ya o no
502
     *
503
     * @param string $route
504
     * @param array|null $action
505
     * @param types\Controller $class
506
     * @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...
507
     */
508
    protected function executeCachedRoute($route, $action, $class, $params = NULL)
509
    {
510 1
        Logger::log('Executing route ' . $route, LOG_INFO);
511
        $action['params'] = array_merge($action['params'], $params, Request::getInstance()->getQueryParams());
512 1
        Security::getInstance()->setSessionKey("__CACHE__", $action);
513 1
        $cache = Cache::needCache();
514 1
        $execute = TRUE;
515 1
        if (FALSE !== $cache && Config::getInstance()->getDebugMode() === FALSE && $action['http'] === 'GET') {
516 1
            list($path, $cacheDataName) = $this->cache->getRequestCacheHash();
517 1
            $cachedData = $this->cache->readFromCache("json" . DIRECTORY_SEPARATOR . $path . $cacheDataName,
518
                $cache, null);
0 ignored issues
show
Bug introduced by
It seems like $cache defined by \PSFS\base\Cache::needCache() on line 513 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...
519 1
            if (NULL !== $cachedData) {
520 1
                $headers = $this->cache->readFromCache("json" . DIRECTORY_SEPARATOR . $path . $cacheDataName . ".headers",
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 122 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...
521 1
                    $cache, null, Cache::JSON);
0 ignored issues
show
Bug introduced by
It seems like $cache defined by \PSFS\base\Cache::needCache() on line 513 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...
522 1
                Template::getInstance()->renderCache($cachedData, $headers);
523
                $execute = FALSE;
524 1
            }
525 1
        }
526
        if ($execute) {
527 1
            Logger::log(_('Start executing action'), LOG_DEBUG);
528
            if (false === call_user_func_array(array($class, $action['method']), $params)) {
529
                Logger::log(_('An error ocurred trying to execute the action'), LOG_ERR, [error_get_last()]);
530
            }
531
        }
532
    }
533
534
    /**
535
     * Parse slugs to create translations
536
     *
537
     * @param string $absoluteTranslationFileName
538
     */
539
    private function generateSlugs($absoluteTranslationFileName)
540
    {
541
        $translations = I18nHelper::generateTranslationsFile($absoluteTranslationFileName);
542
        foreach ($this->routing as $key => &$info) {
543
            $keyParts = $key;
544
            if (FALSE === strstr("#|#", $key)) {
545
                $keyParts = explode("#|#", $key);
546
                $keyParts = array_key_exists(1, $keyParts) ? $keyParts[1] : '';
547
            }
548
            $slug = RouterHelper::slugify($keyParts);
549
            if (NULL !== $slug && !array_key_exists($slug, $translations)) {
550
                $translations[$slug] = $key;
551
                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...
552
            }
553
            $this->slugs[$slug] = $key;
554
            $info["slug"] = $slug;
555
        }
556
    }
557
558
}
559