Passed
Pull Request — 1.2 (#558)
by
unknown
09:10
created

RouteServiceProvider::registerMacros()   D

Complexity

Conditions 18
Paths 1

Size

Total Lines 72
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 31
CRAP Score 21.6905

Importance

Changes 0
Metric Value
cc 18
eloc 42
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 72
ccs 31
cts 40
cp 0.775
crap 21.6905
rs 4.8666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

149
    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...
150
    {
151 59
        Route::aliasMiddleware('supportSubdomainRouting', SupportSubdomainRouting::class);
152 59
        Route::aliasMiddleware('impersonate', Impersonate::class);
153 59
        Route::aliasMiddleware('twill_auth', \Illuminate\Auth\Middleware\Authenticate::class);
154 59
        Route::aliasMiddleware('twill_guest', RedirectIfAuthenticated::class);
155 59
        Route::aliasMiddleware('validateBackHistory', ValidateBackHistory::class);
156 59
    }
157
158
    /**
159
     * Registers Route macros.
160
     *
161
     * @return void
162
     */
163 59
    protected function registerMacros()
164
    {
165
        Route::macro('moduleShowWithPreview', function ($moduleName, $routePrefix = null, $controllerName = null) {
166
            if ($routePrefix === null) {
167
                $routePrefix = $moduleName;
168
            }
169
170
            if ($controllerName === null) {
171
                $controllerName = ucfirst(Str::plural($moduleName));
172
            }
173
174
            $routePrefix = empty($routePrefix) ? '/' : (Str::startsWith($routePrefix, '/') ? $routePrefix : '/' . $routePrefix);
175
            $routePrefix = Str::endsWith($routePrefix, '/') ? $routePrefix : $routePrefix . '/';
176
177
            Route::name($moduleName . '.show')->get($routePrefix . '{slug}', $controllerName . 'Controller@show');
178
            Route::name($moduleName . '.preview')->get('/admin-preview' . $routePrefix . '{slug}', $controllerName . 'Controller@show')->middleware(['web', 'twill_auth:twill_users', 'can:list']);
179 59
        });
180
181
        Route::macro('module', function ($slug, $options = [], $resource_options = [], $resource = true) {
182
183 59
            $slugs = explode('.', $slug);
184 59
            $prefixSlug = str_replace('.', "/", $slug);
185 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...
186
            $className = implode("", array_map(function ($s) {
187 59
                return ucfirst(Str::singular($s));
188 59
            }, $slugs));
189
190 59
            $customRoutes = $defaults = ['reorder', 'publish', 'bulkPublish', 'browser', 'feature', 'bulkFeature', 'tags', 'preview', 'restore', 'bulkRestore', 'forceDelete', 'bulkForceDelete', 'bulkDelete', 'restoreRevision'];
191
192 59
            if (isset($options['only'])) {
193
                $customRoutes = array_intersect($defaults, (array) $options['only']);
194 59
            } elseif (isset($options['except'])) {
195 59
                $customRoutes = array_diff($defaults, (array) $options['except']);
196
            }
197
198 59
            $groupPrefix = trim(str_replace('/', '.', Route::getLastGroupPrefix()), '.');
199
200 59
            if (!empty(config('twill.admin_app_path'))) {
201 55
                $groupPrefix = ltrim(str_replace(config('twill.admin_app_path'), '', $groupPrefix), '.');
202
            }
203
204 59
            $customRoutePrefix = !empty($groupPrefix) ? "{$groupPrefix}.{$slug}" : "{$slug}";
205
206 59
            foreach ($customRoutes as $route) {
207 59
                $routeSlug = "{$prefixSlug}/{$route}";
208 59
                $mapping = ['as' => $customRoutePrefix . ".{$route}", 'uses' => "{$className}Controller@{$route}"];
209
210 59
                if (in_array($route, ['browser', 'tags'])) {
211 59
                    Route::get($routeSlug, $mapping);
212
                }
213
214 59
                if (in_array($route, ['restoreRevision'])) {
215 59
                    Route::get($routeSlug . "/{id}", $mapping);
216
                }
217
218 59
                if (in_array($route, ['publish', 'feature', 'restore', 'forceDelete'])) {
219 59
                    Route::put($routeSlug, $mapping);
220
                }
221
222 59
                if (in_array($route, ['preview'])) {
223 59
                    Route::put($routeSlug . "/{id}", $mapping);
224
                }
225
226 59
                if (in_array($route, ['reorder', 'bulkPublish', 'bulkFeature', 'bulkDelete', 'bulkRestore', 'bulkForceDelete'])) {
227 59
                    Route::post($routeSlug, $mapping);
228
                }
229
            }
230
231 59
            if ($resource) {
232 59
                $customRoutePrefix = !empty($groupPrefix) ? "{$groupPrefix}." : "";
233
                Route::group(['as' => $customRoutePrefix], function () use ($slug, $className, $resource_options) {
234 59
                    Route::resource($slug, "{$className}Controller", $resource_options);
235 59
                });
236
            }
237 59
        });
238 59
    }
239
}
240