Passed
Push — master ( 658447...16f32d )
by Fran
03:59
created

Router   F

Complexity

Total Complexity 92

Size/Duplication

Total Lines 487
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 17

Test Coverage

Coverage 48.08%

Importance

Changes 0
Metric Value
dl 0
loc 487
ccs 100
cts 208
cp 0.4808
rs 1.5789
c 0
b 0
f 0
wmc 92
lcom 1
cbo 17

23 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A init() 0 11 3
A httpNotFound() 0 21 3
A getSlugs() 0 4 1
A getAllRoutes() 0 10 3
B execute() 0 22 4
C searchAction() 0 24 8
A sentAuthHeader() 0 4 1
C checkExternalModules() 0 26 8
A generateRouting() 0 15 3
B hydrateRouting() 0 17 6
A inspectDir() 0 11 2
A exists() 0 4 3
D addRouting() 0 26 10
B extractDomain() 0 15 5
A simpatize() 0 10 1
B getRoute() 0 17 10
A getAdminRoutes() 0 4 1
A getAdmin() 0 4 1
A getDomains() 0 4 2
A checkAction() 0 11 4
B executeCachedRoute() 0 27 6
B generateSlugs() 0 18 6

How to fix   Complexity   

Complex Class

Complex classes like Router often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Router, and based on these observations, apply Extract Interface, too.

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\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\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
28
    use SingletonTrait;
29
30
    protected $routing;
31
    protected $slugs;
32
    private $domains;
33
    /**
34
     * @var Finder $finder
35
     */
36
    private $finder;
37
    /**
38
     * @var \PSFS\base\Cache $cache
39
     */
40
    private $cache;
41
    /**
42
     * @var bool headersSent
43
     */
44
    protected $headersSent = false;
45
46
    /**
47
     * Constructor Router
48
     * @throws ConfigException
49
     */
50 6
    public function __construct()
51
    {
52 6
        $this->finder = new Finder();
53 6
        $this->cache = Cache::getInstance();
54 6
        $this->init();
55 6
    }
56
57
    /**
58
     * Inicializador Router
59
     * @throws ConfigException
60
     */
61 1
    public function init()
62
    {
63 1
        if (!file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . "urls.json") || Config::getInstance()->getDebugMode()) {
64 1
            $this->hydrateRouting();
65 1
            $this->simpatize();
66
        } else {
67 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...
68 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...
69 1
            $this->checkExternalModules(false);
70
        }
71 1
    }
72
73
    /**
74
     * Método que deriva un error HTTP de página no encontrada
75
     *
76
     * @param \Exception $e
77
     *
78
     * @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...
79
     */
80
    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...
81
    {
82
        Logger::log('Throw not found exception');
83
        if (NULL === $e) {
84
            Logger::log('Not found page throwed without previous exception', LOG_WARNING);
85
            $e = new \Exception(_('Page not found'), 404);
86
        }
87
        $template = Template::getInstance()->setStatus($e->getCode());
88
        if (preg_match('/json/i', Request::getInstance()->getServer('CONTENT_TYPE'))) {
89
            return $template->output(json_encode(array(
90
                "success" => FALSE,
91
                "error" => $e->getMessage(),
92
            )), 'application/json');
93
        } else {
94
            return $template->render('error.html.twig', array(
95
                'exception' => $e,
96
                'trace' => $e->getTraceAsString(),
97
                'error_page' => TRUE,
98
            ));
99
        }
100
    }
101
102
    /**
103
     * Método que devuelve las rutas
104
     * @return string|null
105
     */
106
    public function getSlugs()
107
    {
108
        return $this->slugs;
109
    }
110
111
    /**
112
     * Method that extract all routes in the platform
113
     * @return array
114
     */
115
    public function getAllRoutes()
116
    {
117
        $routes = [];
118
        foreach ($this->routing as $path => $route) {
119
            if (array_key_exists('slug', $route)) {
120
                $routes[$route['slug']] = $path;
121
            }
122
        }
123
        return $routes;
124
    }
125
126
    /**
127
     * Método que calcula el objeto a enrutar
128
     *
129
     * @param string|null $route
130
     *
131
     * @throws \Exception
132
     * @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...
133
     */
134
    public function execute($route)
135
    {
136
        Logger::log('Executing the request');
137
        try {
138
            //Check CORS for requests
139
            RequestHelper::checkCORS();
140
            // Checks restricted access
141
            SecurityHelper::checkRestrictedAccess($route);
142
            //Search action and execute
143
            $this->searchAction($route);
144
        } catch (AccessDeniedException $e) {
145
            Logger::log(_('Solicitamos credenciales de acceso a zona restringida'));
146
            return Admin::staticAdminLogon($route);
147
        } catch (RouterException $r) {
148
            Logger::log($r->getMessage(), LOG_WARNING);
149
        } catch (\Exception $e) {
150
            Logger::log($e->getMessage(), LOG_ERR);
151
            throw $e;
152
        }
153
154
        return $this->httpNotFound();
155
    }
156
157
    /**
158
     * Método que busca el componente que ejecuta la ruta
159
     *
160
     * @param string $route
161
     *
162
     * @throws \PSFS\base\exception\RouterException
163
     */
164
    protected function searchAction($route)
165
    {
166
        Logger::log('Searching action to execute: ' . $route, LOG_INFO);
167
        //Revisamos si tenemos la ruta registrada
168
        $parts = parse_url($route);
169
        $path = (array_key_exists('path', $parts)) ? $parts['path'] : $route;
170
        $httpRequest = Request::getInstance()->getMethod();
171
        foreach ($this->routing as $pattern => $action) {
172
            list($httpMethod, $routePattern) = RouterHelper::extractHttpRoute($pattern);
173
            $matched = RouterHelper::matchRoutePattern($routePattern, $path);
174
            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...
175
                $get = RouterHelper::extractComponents($route, $routePattern);
176
                /** @var $class \PSFS\base\types\Controller */
177
                $class = RouterHelper::getClassToCall($action);
178
                try {
179
                    $this->executeCachedRoute($route, $action, $class, $get);
180
                } catch (\Exception $e) {
181
                    Logger::log($e->getMessage(), LOG_ERR);
182
                    throw new RouterException($e->getMessage(), 404, $e);
183
                }
184
            }
185
        }
186
        throw new RouterException(_("Ruta no encontrada"));
187
    }
188
189
    /**
190
     * Método que manda las cabeceras de autenticación
191
     * @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...
192
     */
193
    protected function sentAuthHeader()
194
    {
195
        return AdminServices::getInstance()->setAdminHeaders();
196
    }
197
198
    /**
199
     * Method that check if the proyect has sub project to include
200
     * @param boolean $hydrateRoute
201
     */
202 1
    private function checkExternalModules($hydrateRoute = true)
203
    {
204 1
        $externalModules = Config::getParam('modules.extend');
205 1
        if (null !== $externalModules) {
206
            $externalModules = explode(',', $externalModules);
207
            foreach ($externalModules as &$module) {
208
                $module = preg_replace('/(\\\|\/)/', DIRECTORY_SEPARATOR, $module);
209
                $externalModulePath = VENDOR_DIR . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . 'src';
210
                if (file_exists($externalModulePath)) {
211
                    $externalModule = $this->finder->directories()->in($externalModulePath)->depth(0);
212
                    if (!empty($externalModule)) {
213
                        foreach ($externalModule as $modulePath) {
214
                            $extModule = $modulePath->getBasename();
215
                            $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...
216
                            if (file_exists($moduleAutoloader)) {
217
                                @include $moduleAutoloader;
218
                                if($hydrateRoute) {
219
                                    $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...
220
                                }
221
                            }
222
                        }
223
                    }
224
                }
225
            }
226
        }
227 1
    }
228
229
    /**
230
     * Method that gather all the routes in the project
231
     */
232 1
    private function generateRouting()
233
    {
234 1
        $base = SOURCE_DIR;
235 1
        $modulesPath = realpath(CORE_DIR);
236 1
        $this->routing = $this->inspectDir($base, "PSFS", array());
237 1
        if (file_exists($modulesPath)) {
238
            $modules = $this->finder->directories()->in($modulesPath)->depth(0);
239
            foreach ($modules as $modulePath) {
240
                $module = $modulePath->getBasename();
241
                $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...
242
            }
243
        }
244 1
        $this->checkExternalModules();
245 1
        $this->cache->storeData(CONFIG_DIR . DIRECTORY_SEPARATOR . "domains.json", $this->domains, Cache::JSON, TRUE);
246 1
    }
247
248
    /**
249
     * Método que regenera el fichero de rutas
250
     * @throws ConfigException
251
     */
252 1
    public function hydrateRouting()
253
    {
254 1
        $this->generateRouting();
255 1
        $home = Config::getInstance()->get('home_action');
256 1
        if (NULL !== $home || $home !== '') {
257 1
            $home_params = NULL;
258 1
            foreach ($this->routing as $pattern => $params) {
259 1
                list($method, $route) = RouterHelper::extractHttpRoute($pattern);
260 1
                if (preg_match("/" . preg_quote($route, "/") . "$/i", "/" . $home)) {
261 1
                    $home_params = $params;
262
                }
263
            }
264 1
            if (NULL !== $home_params) {
265
                $this->routing['/'] = $home_params;
266
            }
267
        }
268 1
    }
269
270
    /**
271
     * Método que inspecciona los directorios en busca de clases que registren rutas
272
     *
273
     * @param string $origen
274
     * @param string $namespace
275
     * @param array $routing
276
     *
277
     * @return array
278
     * @throws ConfigException
279
     */
280 1
    private function inspectDir($origen, $namespace = 'PSFS', $routing = [])
281
    {
282 1
        $files = $this->finder->files()->in($origen)->path('/(controller|api)/i')->depth(1)->name("*.php");
283 1
        foreach ($files as $file) {
284 1
            $filename = str_replace("/", '\\', str_replace($origen, '', $file->getPathname()));
285 1
            $routing = $this->addRouting($namespace . str_replace('.php', '', $filename), $routing, $namespace);
286
        }
287 1
        $this->finder = new Finder();
288
289 1
        return $routing;
290
    }
291
292
    /**
293
     * Checks that a namespace exists
294
     * @param string $namespace
295
     * @return bool
296
     */
297 1
    public static function exists($namespace)
298
    {
299 1
        return (class_exists($namespace) || interface_exists($namespace) || trait_exists($namespace));
300
    }
301
302
    /**
303
     * Método que añade nuevas rutas al array de referencia
304
     *
305
     * @param string $namespace
306
     * @param array $routing
307
     * @param string $module
308
     *
309
     * @return array
310
     * @throws ConfigException
311
     */
312 1
    private function addRouting($namespace, &$routing, $module = 'PSFS')
313
    {
314 1
        if (self::exists($namespace)) {
315 1
            $reflection = new \ReflectionClass($namespace);
316 1
            if (FALSE === $reflection->isAbstract() && FALSE === $reflection->isInterface()) {
317 1
                $this->extractDomain($reflection);
318 1
                $classComments = $reflection->getDocComment();
319 1
                preg_match('/@api\ (.*)\n/im', $classComments, $apiPath);
320 1
                $api = '';
321 1
                if (count($apiPath)) {
322
                    $api = array_key_exists(1, $apiPath) ? $apiPath[1] : $api;
323
                }
324 1
                foreach ($reflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
325 1
                    if (preg_match('/@route\ /i', $method->getDocComment())) {
326 1
                        list($route, $info) = RouterHelper::extractRouteInfo($method, $api, $module);
327 1
                        if (null !== $route && null !== $info) {
328 1
                            $info['class'] = $namespace;
329 1
                            $routing[$route] = $info;
330
                        }
331
                    }
332
                }
333
            }
334
        }
335
336 1
        return $routing;
337
    }
338
339
    /**
340
     * Método que extrae de la ReflectionClass los datos necesarios para componer los dominios en los templates
341
     *
342
     * @param \ReflectionClass $class
343
     *
344
     * @return Router
345
     * @throws ConfigException
346
     */
347 1
    protected function extractDomain(\ReflectionClass $class)
348
    {
349
        //Calculamos los dominios para las plantillas
350 1
        if ($class->hasConstant("DOMAIN") && !$class->isAbstract()) {
351 1
            if (!$this->domains) {
352 1
                $this->domains = [];
353
            }
354 1
            $domain = "@" . $class->getConstant("DOMAIN") . "/";
355 1
            if (!array_key_exists($domain, $this->domains)) {
356 1
                $this->domains[$domain] = RouterHelper::extractDomainInfo($class, $domain);
357
            }
358
        }
359
360 1
        return $this;
361
    }
362
363
    /**
364
     * Método que genera las urls amigables para usar dentro del framework
365
     * @return Router
366
     */
367 1
    public function simpatize()
368
    {
369 1
        $translationFileName = "translations" . DIRECTORY_SEPARATOR . "routes_translations.php";
370 1
        $absoluteTranslationFileName = CACHE_DIR . DIRECTORY_SEPARATOR . $translationFileName;
371 1
        $this->generateSlugs($absoluteTranslationFileName);
372 1
        GeneratorHelper::createDir(CONFIG_DIR);
373 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...
374
375 1
        return $this;
376
    }
377
378
    /**
379
     * Método que devuelve una ruta del framework
380
     *
381
     * @param string $slug
382
     * @param boolean $absolute
383
     * @param array $params
384
     *
385
     * @return string|null
386
     * @throws RouterException
387
     */
388 1
    public function getRoute($slug = '', $absolute = FALSE, $params = [])
389
    {
390 1
        if (strlen($slug) === 0) {
391
            return ($absolute) ? Request::getInstance()->getRootUrl() . '/' : '/';
392
        }
393 1
        if (NULL === $slug || !array_key_exists($slug, $this->slugs)) {
394
            throw new RouterException(_("No existe la ruta especificada"));
395
        }
396 1
        $url = ($absolute) ? Request::getInstance()->getRootUrl() . $this->slugs[$slug] : $this->slugs[$slug];
397 1
        if (!empty($params)) foreach ($params as $key => $value) {
398
            $url = str_replace("{" . $key . "}", $value, $url);
399 1
        } elseif (!empty($this->routing[$this->slugs[$slug]]["default"])) {
400 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...
401
        }
402
403 1
        return preg_replace('/(GET|POST|PUT|DELETE|ALL)\#\|\#/', '', $url);
404
    }
405
406
    /**
407
     * Método que devuelve las rutas de administración
408
     * @return array
409
     */
410 2
    public function getAdminRoutes()
411
    {
412 2
        return AdminHelper::getAdminRoutes($this->routing);
413
    }
414
415
    /**
416
     * Método que devuelve le controlador del admin
417
     * @return Admin
418
     */
419
    public function getAdmin()
420
    {
421
        return Admin::getInstance();
422
    }
423
424
    /**
425
     * Método que extrae los dominios
426
     * @return array
427
     */
428
    public function getDomains()
429
    {
430
        return $this->domains ?: [];
431
    }
432
433
    /**
434
     * @param $class
435
     * @param $method
436
     * @param array $params
437
     * @return \ReflectionMethod
438
     */
439
    private function checkAction($class, $method, array $params)
440
    {
441
        $action = new \ReflectionMethod($class, $method);
442
443
        foreach ($action->getParameters() as $parameter) {
444
            if (!$parameter->isOptional() && !array_key_exists($parameter->getName(), $params)) {
445
                throw new RouterException('Required parameters not sent');
446
            }
447
        }
448
        return $action;
449
    }
450
451
    /**
452
     * Método que ejecuta una acción del framework y revisa si lo tenemos cacheado ya o no
453
     *
454
     * @param string $route
455
     * @param array|null $action
456
     * @param types\Controller $class
457
     * @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...
458
     */
459
    protected function executeCachedRoute($route, $action, $class, $params = NULL)
460
    {
461
        Logger::log('Executing route ' . $route, LOG_INFO);
462
        Security::getInstance()->setSessionKey("__CACHE__", $action);
463
        $cache = Cache::needCache();
464
        $execute = TRUE;
465
        if (FALSE !== $cache && Config::getInstance()->getDebugMode() === FALSE) {
466
            $cacheDataName = $this->cache->getRequestCacheHash();
467
            $tmpDir = substr($cacheDataName, 0, 2) . DIRECTORY_SEPARATOR . substr($cacheDataName, 2, 2) . DIRECTORY_SEPARATOR;
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 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...
468
            $cachedData = $this->cache->readFromCache("json" . DIRECTORY_SEPARATOR . $tmpDir . $cacheDataName,
469
                $cache, function () {
0 ignored issues
show
Bug introduced by
It seems like $cache defined by \PSFS\base\Cache::needCache() on line 463 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
                });
471
            if (NULL !== $cachedData) {
472
                $headers = $this->cache->readFromCache("json" . DIRECTORY_SEPARATOR . $tmpDir . $cacheDataName . ".headers",
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 124 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...
473
                    $cache, function () {
0 ignored issues
show
Bug introduced by
It seems like $cache defined by \PSFS\base\Cache::needCache() on line 463 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...
474
                    }, Cache::JSON);
475
                Template::getInstance()->renderCache($cachedData, $headers);
476
                $execute = FALSE;
477
            }
478
        }
479
        if ($execute) {
480
            Logger::log(_('Start executing action'), LOG_DEBUG);
481
            if (false === call_user_func_array(array($class, $action['method']), $params)) {
482
                Logger::log(_('An error ocurred trying to execute the action'), LOG_ERR, [error_get_last()]);
483
            }
484
        }
485
    }
486
487
    /**
488
     * Parse slugs to create translations
489
     *
490
     * @param string $absoluteTranslationFileName
491
     */
492 1
    private function generateSlugs($absoluteTranslationFileName)
493
    {
494 1
        $translations = I18nHelper::generateTranslationsFile($absoluteTranslationFileName);
495 1
        foreach ($this->routing as $key => &$info) {
496 1
            $keyParts = $key;
497 1
            if (FALSE === strstr("#|#", $key)) {
498 1
                $keyParts = explode("#|#", $key);
499 1
                $keyParts = array_key_exists(1, $keyParts) ? $keyParts[1] : '';
500
            }
501 1
            $slug = RouterHelper::slugify($keyParts);
502 1
            if (NULL !== $slug && !array_key_exists($slug, $translations)) {
503 1
                $translations[$slug] = $key;
504 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...
505
            }
506 1
            $this->slugs[$slug] = $key;
507 1
            $info["slug"] = $slug;
508
        }
509 1
    }
510
511
}
512