Passed
Pull Request — 2.x (#729)
by Antonio Carlos
06:06
created

RouteServiceProvider   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 366
Duplicated Lines 0 %

Test Coverage

Coverage 77.33%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
eloc 206
dl 0
loc 366
ccs 133
cts 172
cp 0.7733
rs 9.84
c 5
b 0
f 0
wmc 32

6 Methods

Rating   Name   Duplication   Size   Complexity  
B mapInternalRoutes() 0 99 7
A boot() 0 5 1
A registerRouteMiddlewares() 0 17 1
A map() 0 16 1
F registerMacros() 0 176 21
A mapHostRoutes() 0 14 1
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 A17\Twill\Services\Routing\HasRoutes;
12
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
13
use Illuminate\Routing\Router;
14
use Illuminate\Support\Arr;
15
use Illuminate\Support\Facades\Route;
16
use Illuminate\Support\Str;
17
18
class RouteServiceProvider extends ServiceProvider
19
{
20
    use HasRoutes;
0 ignored issues
show
Bug introduced by
The trait A17\Twill\Services\Routing\HasRoutes requires the property $manager which is not provided by A17\Twill\RouteServiceProvider.
Loading history...
21
22
    protected $namespace = 'A17\Twill\Http\Controllers';
23
24
    /**
25
     * Bootstraps the package services.
26
     *
27
     * @return void
28
     */
29 76
    public function boot()
30
    {
31 76
        $this->registerRouteMiddlewares($this->app->get('router'));
32 76
        $this->registerMacros();
33 76
        parent::boot();
34 76
    }
35
36
    /**
37
     * @param Router $router
38
     * @return void
39
     */
40 76
    public function map(Router $router)
41
    {
42 76
        $this->registerRoutePatterns();
43
44 76
        $this->mapHostRoutes(
45 76
            $router,
46 76
            $this->getRouteGroupOptions(),
47 76
            $this->getRouteMiddleware(),
48 76
            $this->supportSubdomainRouting()
49
        );
50
51 76
        $this->mapInternalRoutes(
52 76
            $router,
53 76
            $this->getRouteGroupOptions(),
54 76
            $this->getRouteMiddleware(),
55 76
            $this->supportSubdomainRouting()
56
        );
57 76
    }
58
59 76
    private function mapHostRoutes(
60
        $router,
61
        $groupOptions,
62
        $middlewares,
63
        $supportSubdomainRouting,
64
        $namespace = null
0 ignored issues
show
Unused Code introduced by
The parameter $namespace 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

64
        /** @scrutinizer ignore-unused */ $namespace = null

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...
65
    ) {
66 76
        $this->registerRoutes(
67 76
            $router,
68
            $groupOptions,
69
            $middlewares,
70
            $supportSubdomainRouting,
71 76
            config('twill.namespace', 'App') . '\Http\Controllers\Admin',
72 76
            base_path('routes/admin.php')
73
        );
74 76
    }
75
76 76
    private function mapInternalRoutes(
77
        $router,
78
        $groupOptions,
79
        $middlewares,
80
        $supportSubdomainRouting
81
    ) {
82 76
        $internalRoutes = function ($router) use (
83 76
            $middlewares,
84 76
            $supportSubdomainRouting
85
        ) {
86 76
            $router->group(['middleware' => $middlewares], function ($router) {
87 76
                require __DIR__ . '/../routes/admin.php';
88 76
            });
89
90 76
            $router->group(
91
                [
92 76
                    'middleware' => $supportSubdomainRouting
93
                        ? ['supportSubdomainRouting']
94
                        : [],
95
                ],
96 76
                function ($router) {
97 76
                    require __DIR__ . '/../routes/auth.php';
98 76
                }
99
            );
100
101 76
            $router->group(
102
                [
103 76
                    'middleware' => $this->app->environment('production')
104
                        ? ['twill_auth:twill_users']
105
                        : [],
106
                ],
107 76
                function ($router) {
108 76
                    require __DIR__ . '/../routes/templates.php';
109 76
                }
110
            );
111 76
        };
112
113 76
        $router->group(
114
            $groupOptions + [
115 76
                'namespace' => $this->namespace . '\Admin',
116
            ],
117 76
            function ($router) use ($internalRoutes, $supportSubdomainRouting) {
118 76
                $router->group(
119
                    [
120 76
                        'domain' => config('twill.admin_app_url'),
121
                    ],
122
                    $internalRoutes
123
                );
124
125 76
                if ($supportSubdomainRouting) {
126
                    $router->group(
127
                        [
128
                            'domain' =>
129
                                config('twill.admin_app_subdomain', 'admin') .
130
                                '.{subdomain}.' .
131
                                config('app.url'),
132
                        ],
133
                        $internalRoutes
134
                    );
135
                }
136 76
            }
137
        );
138
139 76
        if (config('twill.templates_on_frontend_domain')) {
140
            $router->group(
141
                [
142
                    'namespace' => $this->namespace . '\Admin',
143
                    'domain' => config('app.url'),
144
                    'middleware' => [
145
                        config('twill.admin_middleware_group', 'web'),
146
                    ],
147
                ],
148
                function ($router) {
149
                    $router->group(
150
                        [
151
                            'middleware' => $this->app->environment(
152
                                'production'
153
                            )
154
                                ? ['twill_auth:twill_users']
155
                                : [],
156
                        ],
157
                        function ($router) {
158
                            require __DIR__ . '/../routes/templates.php';
159
                        }
160
                    );
161
                }
162
            );
163
        }
164
165
        if (
166 76
            config('twill.media_library.image_service') ===
167 76
            'A17\Twill\Services\MediaLibrary\Glide'
168
        ) {
169
            $router
170 76
                ->get(
171 76
                    '/' . config('twill.glide.base_path') . '/{path}',
172 76
                    GlideController::class
173
                )
174 76
                ->where('path', '.*');
175
        }
176 76
    }
177
178
    /**
179
     * Register Route middleware.
180
     *
181
     * @param Router $router
182
     * @return void
183
     */
184 76
    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

184
    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...
185
    {
186 76
        Route::aliasMiddleware(
187 76
            'supportSubdomainRouting',
188 76
            SupportSubdomainRouting::class
189
        );
190 76
        Route::aliasMiddleware('impersonate', Impersonate::class);
191 76
        Route::aliasMiddleware(
192 76
            'twill_auth',
193 76
            \Illuminate\Auth\Middleware\Authenticate::class
194
        );
195 76
        Route::aliasMiddleware('twill_guest', RedirectIfAuthenticated::class);
196 76
        Route::aliasMiddleware(
197 76
            'validateBackHistory',
198 76
            ValidateBackHistory::class
199
        );
200 76
        Route::aliasMiddleware('localization', Localization::class);
201 76
    }
202
203
    /**
204
     * Registers Route macros.
205
     *
206
     * @return void
207
     */
208 76
    protected function registerMacros()
209
    {
210 76
        Route::macro('moduleShowWithPreview', function (
211
            $moduleName,
212
            $routePrefix = null,
213
            $controllerName = null
214
        ) {
215
            if ($routePrefix === null) {
216
                $routePrefix = $moduleName;
217
            }
218
219
            if ($controllerName === null) {
220
                $controllerName = ucfirst(Str::plural($moduleName));
221
            }
222
223
            $routePrefix = empty($routePrefix)
224
                ? '/'
225
                : (Str::startsWith($routePrefix, '/')
226
                    ? $routePrefix
227
                    : '/' . $routePrefix);
228
            $routePrefix = Str::endsWith($routePrefix, '/')
229
                ? $routePrefix
230
                : $routePrefix . '/';
231
232
            Route::name($moduleName . '.show')->get(
233
                $routePrefix . '{slug}',
234
                $controllerName . 'Controller@show'
235
            );
236
            Route::name($moduleName . '.preview')
237
                ->get(
238
                    '/admin-preview' . $routePrefix . '{slug}',
239
                    $controllerName . 'Controller@show'
240
                )
241
                ->middleware(['web', 'twill_auth:twill_users', 'can:list']);
242 76
        });
243
244 76
        Route::macro('module', function (
245
            $slug,
246
            $options = [],
247
            $resource_options = [],
248
            $resource = true
249
        ) {
250 76
            $slugs = explode('.', $slug);
251 76
            $prefixSlug = str_replace('.', '/', $slug);
252 76
            $_slug = Arr::last($slugs);
0 ignored issues
show
Unused Code introduced by
The assignment to $_slug is dead and can be removed.
Loading history...
253 76
            $className = implode(
254 76
                '',
255 76
                array_map(function ($s) {
256 76
                    return ucfirst(Str::singular($s));
257 76
                }, $slugs)
258
            );
259
260
            $customRoutes = $defaults = [
261 76
                'reorder',
262
                'publish',
263
                'bulkPublish',
264
                'browser',
265
                'feature',
266
                'bulkFeature',
267
                'tags',
268
                'preview',
269
                'restore',
270
                'bulkRestore',
271
                'forceDelete',
272
                'bulkForceDelete',
273
                'bulkDelete',
274
                'restoreRevision',
275
                'duplicate',
276
            ];
277
278 76
            if (isset($options['only'])) {
279
                $customRoutes = array_intersect(
280
                    $defaults,
281
                    (array) $options['only']
282
                );
283 76
            } elseif (isset($options['except'])) {
284 76
                $customRoutes = array_diff(
285 76
                    $defaults,
286 76
                    (array) $options['except']
287
                );
288
            }
289
290
            // Get the current route groups
291 76
            $routeGroups = Route::getGroupStack() ?? [];
292
293
            // Get the name prefix of the last group
294 76
            $lastRouteGroupName = end($routeGroups)['as'] ?? '';
295
296 76
            $groupPrefix = trim(
297 76
                str_replace('/', '.', Route::getLastGroupPrefix()),
298 76
                '.'
299
            );
300
301 76
            if (!empty(config('twill.admin_app_path'))) {
302 76
                $groupPrefix = ltrim(
303 76
                    str_replace(
304 76
                        config('twill.admin_app_path'),
305 76
                        '',
306
                        $groupPrefix
307
                    ),
308 76
                    '.'
309
                );
310
            }
311
312
            // Check if name will be a duplicate, and prevent if needed/allowed
313
            if (
314 76
                !empty($groupPrefix) &&
315 32
                (blank($lastRouteGroupName) ||
316 32
                    config('twill.allow_duplicates_on_route_names', true) ||
317 76
                    !Str::endsWith($lastRouteGroupName, ".{$groupPrefix}."))
318
            ) {
319 32
                $customRoutePrefix = "{$groupPrefix}.{$slug}";
320 32
                $resourceCustomGroupPrefix = "{$groupPrefix}.";
321
            } else {
322 76
                $customRoutePrefix = $slug;
323
324
                // Prevent Laravel from generating route names with duplication
325 76
                $resourceCustomGroupPrefix = '';
326
            }
327
328 76
            foreach ($customRoutes as $route) {
329 76
                $routeSlug = "{$prefixSlug}/{$route}";
330
                $mapping = [
331 76
                    'as' => $customRoutePrefix . ".{$route}",
332 76
                    'uses' => "{$className}Controller@{$route}",
333
                ];
334
335 76
                if (in_array($route, ['browser', 'tags'])) {
336 76
                    Route::get($routeSlug, $mapping);
337
                }
338
339 76
                if (in_array($route, ['restoreRevision'])) {
340 76
                    Route::get($routeSlug . '/{id}', $mapping);
341
                }
342
343
                if (
344 76
                    in_array($route, [
345 76
                        'publish',
346
                        'feature',
347
                        'restore',
348
                        'forceDelete',
349
                    ])
350
                ) {
351 76
                    Route::put($routeSlug, $mapping);
352
                }
353
354 76
                if (in_array($route, ['duplicate'])) {
355 76
                    Route::put($routeSlug . '/{id}', $mapping);
356
                }
357
358 76
                if (in_array($route, ['preview'])) {
359 76
                    Route::put($routeSlug . '/{id}', $mapping);
360
                }
361
362
                if (
363 76
                    in_array($route, [
364 76
                        'reorder',
365
                        'bulkPublish',
366
                        'bulkFeature',
367
                        'bulkDelete',
368
                        'bulkRestore',
369
                        'bulkForceDelete',
370
                    ])
371
                ) {
372 76
                    Route::post($routeSlug, $mapping);
373
                }
374
            }
375
376 76
            if ($resource) {
377 76
                Route::group(
378 76
                    ['as' => $resourceCustomGroupPrefix],
379 76
                    function () use ($slug, $className, $resource_options) {
380 76
                        Route::resource(
381 76
                            $slug,
382 76
                            "{$className}Controller",
383
                            $resource_options
384
                        );
385 76
                    }
386
                );
387
            }
388 76
        });
389 76
    }
390
}
391