Passed
Push — master ( a40012...de4070 )
by Fran
05:30
created

Router::checkExternalModules()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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