RoutesLoader::parseNamespace()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 7
ccs 0
cts 5
cp 0
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 6
1
<?php
2
3
namespace LaravelModulize\Services\Loaders;
4
5
use Illuminate\Support\Facades\Route;
6
use Illuminate\Support\Str;
7
8
class RoutesLoader extends BaseFileLoader
9
{
10
    /**
11
     * Load the files to load and register them
12
     *
13
     * @param string $module
14
     * @return void
15
     */
16
    public function loadFiles(string $module): void
17
    {
18
        $this->getFilesToLoad($module)->each(function ($routeFile) use ($module) {
19
            $this->registerRoute(
20
                $this->parseNamespace($module, $routeFile->getBasename()),
21
                $routeFile->getRealPath()
22
            );
23
        });
24
    }
25
26
    /**
27
     * Retrieve the path where the files to load should be at
28
     *
29
     * @param string $module
30
     * @return string
31
     */
32
    public function getFilesPath(string $module): string
33
    {
34
        return $this->repo->getModulePath($module) . "/Http/Routes";
35
    }
36
37
    /**
38
     * Retrieve the namespace to be used when registering the files
39
     *
40
     * @param string $module
41
     * @return string
42
     */
43
    public function getNamespace(string $module): string
44
    {
45
        return $this->repo
46
            ->getModuleNamespace($module) . '\\Http\\Controllers';
47
    }
48
49
    /**
50
     * Parse the namespace that will be used in the Router
51
     * This enables the user to create as many route files as needed
52
     * If the baseName does not contain 'Routes' the namespace will be at the base Controller
53
     *
54
     * @param string $module
55
     * @param string $baseName
56
     * @return string
57
     */
58
    private function parseNamespace(string $module, string $baseName): string
59
    {
60
        $namespace = Str::contains($baseName, 'Routes')
61
        ? Str::start(Str::studly(Str::before($baseName, 'Routes')), '\\')
62
        : '';
63
64
        return $this->getNamespace($module) . $namespace;
65
    }
66
67
    /**
68
     * First we check if the routes have been cached, if not
69
     * Load the routes while registering the namespace.
70
     *
71
     * @param string $namespace
72
     * @param string $realPath
73
     * @return void
74
     */
75
    private function registerRoute(string $namespace, string $realPath)
76
    {
77
        if (!$this->app->routesAreCached()) {
78
            Route::middleware('api')
79
                ->namespace($namespace)
80
                ->group($realPath);
81
        }
82
    }
83
}
84