Test Failed
Push — master ( cc821f...fdc4d2 )
by Fran
09:36 queued 04:02
created

Router::generateSlugs()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 12.4085

Importance

Changes 0
Metric Value
cc 5
eloc 11
nc 5
nop 1
dl 0
loc 15
ccs 4
cts 12
cp 0.3333
crap 12.4085
rs 8.8571
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\AdminCredentialsException;
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
    /**
30
     * @var array
31
     */
32
    protected $routing = [];
33
    /**
34
     * @var array
35
     */
36
    protected $slugs = [];
37
    /**
38
     * @var array
39
     */
40
    private $domains = [];
41
    /**
42
     * @var Finder $finder
43
     */
44
    private $finder;
45
    /**
46
     * @var \PSFS\base\Cache $cache
47
     */
48
    private $cache;
49
    /**
50
     * @var bool headersSent
51
     */
52
    protected $headersSent = false;
53
    /**
54
     * @var int
55
     */
56
    protected $cacheType = Cache::JSON;
57
58
    /**
59
     * @throws ConfigException
60
     */
61 1
    public function __construct()
62
    {
63 1
        $this->finder = new Finder();
64 1
        $this->cache = Cache::getInstance();
65 1
        $this->init();
66 1
    }
67
68
    /**
69
     * @throws exception\GeneratorException
70
     * @throws ConfigException
71
     */
72 1
    public function init()
73
    {
74 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...
75 1
        if (empty($this->routing) || Config::getInstance()->getDebugMode()) {
76 1
            $this->debugLoad();
77
        } else {
78
            $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...
79
        }
80 1
        $this->checkExternalModules(false);
81 1
        $this->setLoaded();
82 1
    }
83
84
    /**
85
     * @throws exception\GeneratorException
86
     * @throws ConfigException
87
     */
88 1
    private function debugLoad() {
89 1
        Logger::log('Begin routes load');
90 1
        $this->hydrateRouting();
91 1
        $this->simpatize();
92 1
        Logger::log('End routes load');
93 1
    }
94
95
    /**
96
     * @param \Exception|NULL $e
97
     * @param bool $isJson
98
     * @return string
99
     * @throws RouterException
100
     */
101
    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...
102
    {
103
        Logger::log('Throw not found exception');
104
        if (NULL === $e) {
105
            Logger::log('Not found page thrown without previous exception', LOG_WARNING);
106
            $e = new \Exception(_('Page not found'), 404);
107
        }
108
        $template = Template::getInstance()->setStatus($e->getCode());
109
        if ($isJson || false !== stripos(Request::getInstance()->getServer('CONTENT_TYPE'), 'json')) {
110
            $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...
111
            return $template->output(json_encode($response), 'application/json');
112
        }
113
114
        $not_found_route = Config::getParam('route.404');
115
        if(null !== $not_found_route) {
116
            Request::getInstance()->redirect($this->getRoute($not_found_route, true));
117
        } else {
118
            return $template->render('error.html.twig', array(
119
                'exception' => $e,
120
                'trace' => $e->getTraceAsString(),
121
                'error_page' => TRUE,
122
            ));
123
        }
124
    }
125
126
    /**
127
     * @return array
128
     */
129 1
    public function getSlugs()
130
    {
131 1
        return $this->slugs;
132
    }
133
134
    /**
135
     * @return array
136
     */
137 1
    public function getRoutes() {
138 1
        return $this->routing;
139
    }
140
141
    /**
142
     * Method that extract all routes in the platform
143
     * @return array
144
     */
145
    public function getAllRoutes()
146
    {
147
        $routes = [];
148
        foreach ($this->getRoutes() as $path => $route) {
149
            if (array_key_exists('slug', $route)) {
150
                $routes[$route['slug']] = $path;
151
            }
152
        }
153
        return $routes;
154
    }
155
156
    /**
157
     * @param string|null $route
158
     *
159
     * @throws \Exception
160
     * @return string HTML
161
     */
162 1
    public function execute($route)
163
    {
164 1
        Logger::log('Executing the request');
165
        try {
166
            //Search action and execute
167 1
            $this->searchAction($route);
168 1
        } catch (AccessDeniedException $e) {
169
            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...
170
            return Admin::staticAdminLogon($route);
171 1
        } catch (RouterException $r) {
172 1
            Logger::log($r->getMessage(), LOG_WARNING);
173
        } catch (\Exception $e) {
174
            Logger::log($e->getMessage(), LOG_ERR);
175
            throw $e;
176
        }
177
178 1
        throw new RouterException(_('Página no encontrada'), 404);
179
    }
180
181
    /**
182
     * @param $route
183
     * @throws AccessDeniedException
184
     * @throws AdminCredentialsException
185
     * @throws RouterException
186
     * @throws \Exception
187
     */
188 1
    protected function searchAction($route)
189
    {
190 1
        Logger::log('Searching action to execute: ' . $route, LOG_INFO);
191
        //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
            list($httpMethod, $routePattern) = RouterHelper::extractHttpRoute($pattern);
197
            $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);
0 ignored issues
show
Documentation introduced by
$class is of type object<PSFS\base\types\Controller>, but the function expects a string.

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...
207
                    } else {
208
                        throw new RouterException(_('La ruta no es válida'), 400);
209
                    }
210
                } catch (\Exception $e) {
211
                    Logger::log($e->getMessage(), LOG_ERR);
212
                    throw $e;
213
                }
214
            }
215
        }
216 1
        throw new RouterException(_('Ruta no encontrada'));
217
    }
218
219
    /**
220
     * @param array $action
221
     * @param array $params
222
     * @return bool
223
     */
224
    private function checkRequirements(array $action, $params = []) {
225
        if(!empty($params) && !empty($action['requirements'])) {
226
            $checked = 0;
227
            foreach(array_keys($params) as $key) {
228
                if(in_array($key, $action['requirements'], true)) {
229
                    $checked++;
230
                }
231
            }
232
            $valid = count($action['requirements']) === $checked;
233
        } else {
234
            $valid = true;
235
        }
236
        return $valid;
237
    }
238
239
    /**
240
     * @return string HTML
241
     */
242
    protected function sentAuthHeader()
243
    {
244
        return AdminServices::getInstance()->setAdminHeaders();
245
    }
246
247
    /**
248
     * @return string|null
249
     */
250 1
    private function getExternalModules() {
251 1
        $externalModules = Config::getParam('modules.extend', '');
252 1
        $externalModules .= ',psfs/auth';
253 1
        return $externalModules;
254
    }
255
256
    /**
257
     * @param boolean $hydrateRoute
258
     */
259 1
    private function checkExternalModules($hydrateRoute = true)
260
    {
261 1
        $externalModules = $this->getExternalModules();
262 1
        if ('' !== $externalModules) {
263 1
            $externalModules = explode(',', $externalModules);
264 1
            foreach ($externalModules as &$module) {
265 1
                $module = $this->loadExternalModule($hydrateRoute, $module);
266
            }
267
        }
268 1
    }
269
270
    /**
271
     * @throws exception\GeneratorException
272
     * @throws ConfigException
273
     * @throws \InvalidArgumentException
274
     */
275 1
    private function generateRouting()
276
    {
277 1
        $base = SOURCE_DIR;
278 1
        $modulesPath = realpath(CORE_DIR);
279 1
        $this->routing = $this->inspectDir($base, 'PSFS', array());
280 1
        $this->checkExternalModules();
281 1
        if (file_exists($modulesPath)) {
282
            $modules = $this->finder->directories()->in($modulesPath)->depth(0);
283
            if(is_array($modules)) {
284
                foreach ($modules as $modulePath) {
285
                    $module = $modulePath->getBasename();
286
                    $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 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...
287
                }
288
            }
289
        }
290 1
        $this->cache->storeData(CONFIG_DIR . DIRECTORY_SEPARATOR . 'domains.json', $this->domains, Cache::JSON, TRUE);
291 1
    }
292
293
    /**
294
     * @throws exception\GeneratorException
295
     * @throws ConfigException
296
     * @throws \InvalidArgumentException
297
     */
298 1
    public function hydrateRouting()
299
    {
300 1
        $this->generateRouting();
301 1
        $home = Config::getInstance()->get('home.action');
302 1
        if (NULL !== $home || $home !== '') {
303 1
            $home_params = NULL;
304 1
            foreach ($this->routing as $pattern => $params) {
305
                list($method, $route) = RouterHelper::extractHttpRoute($pattern);
306
                if (preg_match('/' . preg_quote($route, '/') . '$/i', '/' . $home)) {
307
                    $home_params = $params;
308
                }
309
            }
310 1
            if (NULL !== $home_params) {
311
                $this->routing['/'] = $home_params;
312
            }
313
        }
314 1
    }
315
316
    /**
317
     * @param string $origen
318
     * @param string $namespace
319
     * @param array $routing
320
     * @return array
321
     * @throws ConfigException
322
     * @throws \InvalidArgumentException
323
     */
324 1
    private function inspectDir($origen, $namespace = 'PSFS', $routing = [])
325
    {
326 1
        $files = $this->finder->files()->in($origen)->path('/(controller|api)/i')->depth(1)->name('*.php');
327 1
        if(is_array($files)) {
328
            foreach ($files as $file) {
329
                $filename = str_replace('/', '\\', str_replace($origen, '', $file->getPathname()));
330
                $routing = $this->addRouting($namespace . str_replace('.php', '', $filename), $routing, $namespace);
331
            }
332
        }
333 1
        $this->finder = new Finder();
334
335 1
        return $routing;
336
    }
337
338
    /**
339
     * @param string $namespace
340
     * @return bool
341
     */
342 2
    public static function exists($namespace)
343
    {
344 2
        return (class_exists($namespace) || interface_exists($namespace) || trait_exists($namespace));
345
    }
346
347
    /**
348
     *
349
     * @param string $namespace
350
     * @param array $routing
351
     * @param string $module
352
     *
353
     * @return array
354
     * @throws ConfigException
355
     */
356
    private function addRouting($namespace, &$routing, $module = 'PSFS')
357
    {
358
        if (self::exists($namespace)) {
359
            if(I18nHelper::checkI18Class($namespace)) {
360
                return $routing;
361
            }
362
            $reflection = new \ReflectionClass($namespace);
363
            if (FALSE === $reflection->isAbstract() && FALSE === $reflection->isInterface()) {
364
                $this->extractDomain($reflection);
365
                $classComments = $reflection->getDocComment();
366
                preg_match('/@api\ (.*)\n/im', $classComments, $apiPath);
367
                $api = '';
368
                if (count($apiPath)) {
369
                    $api = array_key_exists(1, $apiPath) ? $apiPath[1] : $api;
370
                }
371
                foreach ($reflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
372
                    if (preg_match('/@route\ /i', $method->getDocComment())) {
373
                        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...
374
375
                        if (null !== $route && null !== $info) {
376
                            $info['class'] = $namespace;
377
                            $routing[$route] = $info;
378
                        }
379
                    }
380
                }
381
            }
382
        }
383
384
        return $routing;
385
    }
386
387
    /**
388
     *
389
     * @param \ReflectionClass $class
390
     *
391
     * @return Router
392
     * @throws ConfigException
393
     */
394
    protected function extractDomain(\ReflectionClass $class)
395
    {
396
        //Calculamos los dominios para las plantillas
397
        if ($class->hasConstant('DOMAIN') && !$class->isAbstract()) {
398
            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...
399
                $this->domains = [];
400
            }
401
            $domain = '@' . $class->getConstant('DOMAIN') . '/';
402
            if (!array_key_exists($domain, $this->domains)) {
403
                $this->domains[$domain] = RouterHelper::extractDomainInfo($class, $domain);
404
            }
405
        }
406
407
        return $this;
408
    }
409
410
    /**
411
     * @return $this
412
     * @throws exception\GeneratorException
413
     * @throws ConfigException
414
     */
415 1
    public function simpatize()
416
    {
417 1
        $translationFileName = 'translations' . DIRECTORY_SEPARATOR . 'routes_translations.php';
418 1
        $absoluteTranslationFileName = CACHE_DIR . DIRECTORY_SEPARATOR . $translationFileName;
419 1
        $this->generateSlugs($absoluteTranslationFileName);
420 1
        GeneratorHelper::createDir(CONFIG_DIR);
421 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...
422
423 1
        return $this;
424
    }
425
426
    /**
427
     * @param string $slug
428
     * @param boolean $absolute
429
     * @param array $params
430
     *
431
     * @return string|null
432
     * @throws RouterException
433
     */
434 3
    public function getRoute($slug = '', $absolute = FALSE, array $params = [])
435
    {
436 3
        if ('' === $slug) {
437 2
            return $absolute ? Request::getInstance()->getRootUrl() . '/' : '/';
438
        }
439 3
        if (!is_array($this->slugs) || !array_key_exists($slug, $this->slugs)) {
440 3
            throw new RouterException(_('No existe la ruta especificada'));
441
        }
442
        $url = $absolute ? Request::getInstance()->getRootUrl() . $this->slugs[$slug] : $this->slugs[$slug];
443
        if (!empty($params)) {
444
            foreach ($params as $key => $value) {
445
                $url = str_replace('{' . $key . '}', $value, $url);
446
            }
447
        } elseif (!empty($this->routing[$this->slugs[$slug]]['default'])) {
448
            $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 166 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...
449
        }
450
451
        return preg_replace('/(GET|POST|PUT|DELETE|ALL)\#\|\#/', '', $url);
452
    }
453
454
    /**
455
     * @deprecated
456
     * @return array
457
     */
458
    public function getAdminRoutes()
459
    {
460
        return AdminHelper::getAdminRoutes($this->routing);
461
    }
462
463
    /**
464
     * @deprecated
465
     * @return Admin
466
     */
467
    public function getAdmin()
468
    {
469
        return Admin::getInstance();
470
    }
471
472
    /**
473
     * @return array
474
     */
475 1
    public function getDomains()
476
    {
477 1
        return $this->domains ?: [];
478
    }
479
480
    /**
481
     * @param string $route
482
     * @param array $action
483
     * @param string $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
     * @throws exception\GeneratorException
486
     * @throws ConfigException
487
     */
488
    protected function executeCachedRoute($route, $action, $class, $params = NULL)
489
    {
490
        Logger::log('Executing route ' . $route, LOG_INFO);
491
        $action['params'] = array_merge($action['params'], $params, Request::getInstance()->getQueryParams());
492
        Security::getInstance()->setSessionKey(Cache::CACHE_SESSION_VAR, $action);
493
        $cache = Cache::needCache();
494
        $execute = TRUE;
495
        if (FALSE !== $cache && $action['http'] === 'GET' && Config::getParam('debug') === FALSE) {
496
            list($path, $cacheDataName) = $this->cache->getRequestCacheHash();
497
            $cachedData = $this->cache->readFromCache('json' . DIRECTORY_SEPARATOR . $path . $cacheDataName,
498
                $cache);
0 ignored issues
show
Bug introduced by
It seems like $cache defined by \PSFS\base\Cache::needCache() on line 493 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...
499
            if (NULL !== $cachedData) {
500
                $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...
501
                    $cache, null, Cache::JSON);
0 ignored issues
show
Bug introduced by
It seems like $cache defined by \PSFS\base\Cache::needCache() on line 493 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...
502
                Template::getInstance()->renderCache($cachedData, $headers);
503
                $execute = FALSE;
504
            }
505
        }
506
        if ($execute) {
507
            Logger::log(_('Start executing action'));
508
            if (false === call_user_func_array(array($class, $action['method']), $params)) {
509
                Logger::log(_('An error occurred trying to execute the action'), LOG_ERR, [error_get_last()]);
510
            }
511
        }
512
    }
513
514
    /**
515
     * Parse slugs to create translations
516
     *
517
     * @param string $absoluteTranslationFileName
518
     */
519 1
    private function generateSlugs($absoluteTranslationFileName)
520
    {
521 1
        $translations = I18nHelper::generateTranslationsFile($absoluteTranslationFileName);
522 1
        foreach ($this->routing as $key => &$info) {
523
            $keyParts = explode('#|#', $key);
524
            $keyParts = array_key_exists(1, $keyParts) ? $keyParts[1] : $keyParts[0];
525
            $slug = RouterHelper::slugify($keyParts);
526
            if (NULL !== $slug && !array_key_exists($slug, $translations)) {
527
                $translations[$slug] = $info['label'];
528
                file_put_contents($absoluteTranslationFileName, "\$translations[\"{$slug}\"] = _(\"{$info['label']}\");\n", FILE_APPEND);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 137 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...
529
            }
530
            $this->slugs[$slug] = $key;
531
            $info['slug'] = $slug;
532
        }
533 1
    }
534
535
    /**
536
     * @param bool $hydrateRoute
537
     * @param $modulePath
538
     * @param $externalModulePath
539
     */
540
    private function loadExternalAutoloader($hydrateRoute, SplFileInfo $modulePath, $externalModulePath)
541
    {
542
        $extModule = $modulePath->getBasename();
543
        $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...
544
        if(file_exists($moduleAutoloader)) {
545
            include_once $moduleAutoloader;
546
            if ($hydrateRoute) {
547
                $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...
548
            }
549
        }
550
    }
551
552
    /**
553
     * @param $hydrateRoute
554
     * @param $module
555
     * @return mixed
556
     */
557 1
    private function loadExternalModule($hydrateRoute, $module)
558
    {
559
        try {
560 1
            $module = preg_replace('/(\\\|\/)/', DIRECTORY_SEPARATOR, $module);
561 1
            $externalModulePath = VENDOR_DIR . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . 'src';
562 1
            $externalModule = $this->finder->directories()->in($externalModulePath)->depth(0);
563
            if(is_array($externalModule)) {
564
                foreach ($externalModule as $modulePath) {
565
                    $this->loadExternalAutoloader($hydrateRoute, $modulePath, $externalModulePath);
566
                }
567
            }
568 1
        } catch (\Exception $e) {
569 1
            Logger::log($e->getMessage(), LOG_WARNING);
570 1
            $module = null;
571
        }
572 1
        return $module;
573
    }
574
575
}
576