Passed
Push — 2.x ( 63a107...267eec )
by Quentin
13:48 queued 09:25
created

RouteServiceProvider   A

Complexity

Total Complexity 38

Size/Duplication

Total Lines 245
Duplicated Lines 0 %

Test Coverage

Coverage 80.17%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 38
eloc 125
c 5
b 0
f 0
dl 0
loc 245
ccs 97
cts 121
cp 0.8017
rs 9.36

6 Methods

Rating   Name   Duplication   Size   Complexity  
B mapInternalRoutes() 0 48 7
A boot() 0 5 1
A registerRouteMiddlewares() 0 8 1
A mapHostRoutes() 0 20 3
D registerMacros() 0 96 21
A map() 0 31 5
1
<?php
2
3
namespace A17\Twill;
4
5
use A17\Twill\Http\Controllers\Front\GlideController;
6
use A17\Twill\Http\Middleware\Impersonate;
7
use A17\Twill\Http\Middleware\Localization;
8
use A17\Twill\Http\Middleware\RedirectIfAuthenticated;
9
use A17\Twill\Http\Middleware\SupportSubdomainRouting;
10
use A17\Twill\Http\Middleware\ValidateBackHistory;
11
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
12
use Illuminate\Routing\Router;
13
use Illuminate\Support\Arr;
14
use Illuminate\Support\Facades\Route;
15
use Illuminate\Support\Str;
16
17
class RouteServiceProvider extends ServiceProvider
18
{
19
    protected $namespace = 'A17\Twill\Http\Controllers';
20
21
    /**
22
     * Bootstraps the package services.
23
     *
24
     * @return void
25
     */
26 59
    public function boot()
27
    {
28 59
        $this->registerRouteMiddlewares($this->app->get('router'));
29 59
        $this->registerMacros();
30 59
        parent::boot();
31 59
    }
32
33
    /**
34
     * @param Router $router
35
     * @return void
36
     */
37 59
    public function map(Router $router)
38
    {
39 59
        if (($patterns = config('twill.admin_route_patterns')) != null) {
40
            if (is_array($patterns)) {
41
                foreach ($patterns as $label => $pattern) {
42
                    Route::pattern($label, $pattern);
43
                }
44
            }
45
        }
46
47
        $groupOptions = [
48 59
            'as' => 'admin.',
49 59
            'middleware' => [config('twill.admin_middleware_group', 'web')],
50 59
            'prefix' => rtrim(ltrim(config('twill.admin_app_path'), '/'), '/'),
51
        ];
52
53
        $middlewares = [
54 59
            'twill_auth:twill_users',
55
            'impersonate',
56
            'validateBackHistory',
57
            'localization',
58
        ];
59
60 59
        $supportSubdomainRouting = config('twill.support_subdomain_admin_routing', false);
61
62 59
        if ($supportSubdomainRouting) {
63
            array_unshift($middlewares, 'supportSubdomainRouting');
64
        }
65
66 59
        $this->mapHostRoutes($router, $groupOptions, $middlewares, $supportSubdomainRouting);
67 59
        $this->mapInternalRoutes($router, $groupOptions, $middlewares, $supportSubdomainRouting);
68 59
    }
69
70 59
    private function mapHostRoutes($router, $groupOptions, $middlewares, $supportSubdomainRouting)
71
    {
72 59
        if (file_exists(base_path('routes/admin.php'))) {
73
            $hostRoutes = function ($router) use ($middlewares) {
74 58
                $router->group([
75 58
                    'namespace' => config('twill.namespace', 'App') . '\Http\Controllers\Admin',
76 58
                    'middleware' => $middlewares,
77
                ], function ($router) {
78 58
                    require base_path('routes/admin.php');
79 58
                });
80 58
            };
81
82 58
            $router->group($groupOptions + [
83 58
                'domain' => config('twill.admin_app_url'),
84
            ], $hostRoutes);
85
86 58
            if ($supportSubdomainRouting) {
87
                $router->group($groupOptions + [
88
                    'domain' => config('twill.admin_app_subdomain', 'admin') . '.{subdomain}.' . config('app.url'),
89
                ], $hostRoutes);
90
            }
91
        }
92 59
    }
93
94 59
    private function mapInternalRoutes($router, $groupOptions, $middlewares, $supportSubdomainRouting)
95
    {
96
        $internalRoutes = function ($router) use ($middlewares, $supportSubdomainRouting) {
97
            $router->group(['middleware' => $middlewares], function ($router) {
98 59
                require __DIR__ . '/../routes/admin.php';
99 59
            });
100
101 59
            $router->group([
102 59
                'middleware' => $supportSubdomainRouting ? ['supportSubdomainRouting'] : [],
103
            ], function ($router) {
104 59
                require __DIR__ . '/../routes/auth.php';
105 59
            });
106
107
            $router->group(['middleware' => $this->app->environment('production') ? ['twill_auth:twill_users'] : []], function ($router) {
108 59
                require __DIR__ . '/../routes/templates.php';
109 59
            });
110 59
        };
111
112 59
        $router->group($groupOptions + [
113 59
            'namespace' => $this->namespace . '\Admin',
114
        ], function ($router) use ($internalRoutes, $supportSubdomainRouting) {
115 59
            $router->group([
116 59
                'domain' => config('twill.admin_app_url'),
117
            ], $internalRoutes);
118
119 59
            if ($supportSubdomainRouting) {
120
                $router->group([
121
                    'domain' => config('twill.admin_app_subdomain', 'admin') . '.{subdomain}.' . config('app.url'),
122
                ], $internalRoutes);
123
            }
124 59
        });
125
126 59
        if (config('twill.templates_on_frontend_domain')) {
127
            $router->group([
128
                'namespace' => $this->namespace . '\Admin',
129
                'domain' => config('app.url'),
130
                'middleware' => [config('twill.admin_middleware_group', 'web')],
131
            ],
132
                function ($router) {
133
                    $router->group(['middleware' => $this->app->environment('production') ? ['twill_auth:twill_users'] : []], function ($router) {
134
                        require __DIR__ . '/../routes/templates.php';
135
                    });
136
                }
137
            );
138
        }
139
140 59
        if (config('twill.media_library.image_service') === 'A17\Twill\Services\MediaLibrary\Glide') {
141 59
            $router->get('/' . config('twill.glide.base_path') . '/{path}', GlideController::class)->where('path', '.*');
142
        }
143 59
    }
144
145
    /**
146
     * Register Route middleware.
147
     *
148
     * @param Router $router
149
     * @return void
150
     */
151 59
    private function registerRouteMiddlewares(Router $router)
0 ignored issues
show
Unused Code introduced by
The parameter $router is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

151
    private function registerRouteMiddlewares(/** @scrutinizer ignore-unused */ Router $router)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
152
    {
153 59
        Route::aliasMiddleware('supportSubdomainRouting', SupportSubdomainRouting::class);
154 59
        Route::aliasMiddleware('impersonate', Impersonate::class);
155 59
        Route::aliasMiddleware('twill_auth', \Illuminate\Auth\Middleware\Authenticate::class);
156 59
        Route::aliasMiddleware('twill_guest', RedirectIfAuthenticated::class);
157 59
        Route::aliasMiddleware('validateBackHistory', ValidateBackHistory::class);
158 59
        Route::aliasMiddleware('localization', Localization::class);
159 59
    }
160
161
    /**
162
     * Registers Route macros.
163
     *
164
     * @return void
165
     */
166 59
    protected function registerMacros()
167
    {
168
        Route::macro('moduleShowWithPreview', function ($moduleName, $routePrefix = null, $controllerName = null) {
169
            if ($routePrefix === null) {
170
                $routePrefix = $moduleName;
171
            }
172
173
            if ($controllerName === null) {
174
                $controllerName = ucfirst(Str::plural($moduleName));
175
            }
176
177
            $routePrefix = empty($routePrefix) ? '/' : (Str::startsWith($routePrefix, '/') ? $routePrefix : '/' . $routePrefix);
178
            $routePrefix = Str::endsWith($routePrefix, '/') ? $routePrefix : $routePrefix . '/';
179
180
            Route::name($moduleName . '.show')->get($routePrefix . '{slug}', $controllerName . 'Controller@show');
181
            Route::name($moduleName . '.preview')->get('/admin-preview' . $routePrefix . '{slug}', $controllerName . 'Controller@show')->middleware(['web', 'twill_auth:twill_users', 'can:list']);
182 59
        });
183
184
        Route::macro('module', function ($slug, $options = [], $resource_options = [], $resource = true) {
185
186 59
            $slugs = explode('.', $slug);
187 59
            $prefixSlug = str_replace('.', "/", $slug);
188 59
            $_slug = Arr::last($slugs);
0 ignored issues
show
Unused Code introduced by
The assignment to $_slug is dead and can be removed.
Loading history...
189
            $className = implode("", array_map(function ($s) {
190 59
                return ucfirst(Str::singular($s));
191 59
            }, $slugs));
192
193 59
            $customRoutes = $defaults = ['reorder', 'publish', 'bulkPublish', 'browser', 'feature', 'bulkFeature', 'tags', 'preview', 'restore', 'bulkRestore', 'forceDelete', 'bulkForceDelete', 'bulkDelete', 'restoreRevision', 'duplicate'];
194
195 59
            if (isset($options['only'])) {
196
                $customRoutes = array_intersect($defaults, (array) $options['only']);
197 59
            } elseif (isset($options['except'])) {
198 59
                $customRoutes = array_diff($defaults, (array) $options['except']);
199
            }
200
201
            // Get the current route groups
202 59
            $routeGroups = Route::getGroupStack() ?? [];
203
204
            // Get the name prefix of the last group
205 59
            $lastRouteGroupName = end($routeGroups)['as'] ?? '';
206
207 59
            $groupPrefix = trim(str_replace('/', '.', Route::getLastGroupPrefix()), '.');
208
209 59
            if (!empty(config('twill.admin_app_path'))) {
210 55
                $groupPrefix = ltrim(str_replace(config('twill.admin_app_path'), '', $groupPrefix), '.');
211
            }
212
213
            // Check if name will be a duplicate, and prevent if needed/allowed
214 59
            if (!empty($groupPrefix) &&
215
                (
216 55
                    blank($lastRouteGroupName) ||
217 55
                    config('twill.allow_duplicates_on_route_names', true) ||
218 59
                    (!Str::endsWith($lastRouteGroupName, ".{$groupPrefix}."))
219
                )
220
            ) {
221 55
                $customRoutePrefix = "{$groupPrefix}.{$slug}";
222 55
                $resourceCustomGroupPrefix = "{$groupPrefix}.";
223
            } else {
224 59
                $customRoutePrefix = $slug;
225
226
                // Prevent Laravel from generating route names with duplication
227 59
                $resourceCustomGroupPrefix = '';
228
            }
229
230 59
            foreach ($customRoutes as $route) {
231 59
                $routeSlug = "{$prefixSlug}/{$route}";
232 59
                $mapping = ['as' => $customRoutePrefix . ".{$route}", 'uses' => "{$className}Controller@{$route}"];
233
234 59
                if (in_array($route, ['browser', 'tags'])) {
235 59
                    Route::get($routeSlug, $mapping);
236
                }
237
238 59
                if (in_array($route, ['restoreRevision'])) {
239 59
                    Route::get($routeSlug . "/{id}", $mapping);
240
                }
241
242 59
                if (in_array($route, ['publish', 'feature', 'restore', 'forceDelete'])) {
243 59
                    Route::put($routeSlug, $mapping);
244
                }
245
246 59
                if (in_array($route, ['duplicate'])) {
247 59
                    Route::put($routeSlug . "/{id}", $mapping);
248
                }
249
250 59
                if (in_array($route, ['preview'])) {
251 59
                    Route::put($routeSlug . "/{id}", $mapping);
252
                }
253
254 59
                if (in_array($route, ['reorder', 'bulkPublish', 'bulkFeature', 'bulkDelete', 'bulkRestore', 'bulkForceDelete'])) {
255 59
                    Route::post($routeSlug, $mapping);
256
                }
257
            }
258
259 59
            if ($resource) {
260
                Route::group(['as' => $resourceCustomGroupPrefix], function () use ($slug, $className, $resource_options) {
261 59
                    Route::resource($slug, "{$className}Controller", $resource_options);
262 59
                });
263
            }
264 59
        });
265 59
    }
266
}
267