Completed
Pull Request — master (#341)
by Cristian
02:11
created

allowCustomGuardDefinitionInRouteGroups()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 1
nop 0
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
1
<?php
2
3
namespace Backpack\Base;
4
5
use Illuminate\Routing\Router;
6
use Illuminate\Support\ServiceProvider;
7
use Route;
8
9
class BaseServiceProvider extends ServiceProvider
10
{
11
    const VERSION = '1.0.0';
12
13
    protected $commands = [
14
        \Backpack\Base\app\Console\Commands\Install::class,
15
        \Backpack\Base\app\Console\Commands\AddSidebarContent::class,
16
        \Backpack\Base\app\Console\Commands\AddCustomRouteContent::class,
17
        \Backpack\Base\app\Console\Commands\Version::class,
18
        \Backpack\Base\app\Console\Commands\CreateUser::class,
19
        \Backpack\Base\app\Console\Commands\PublishBackpackUserModel::class,
20
        \Backpack\Base\app\Console\Commands\PublishBackpackMiddleware::class,
21
    ];
22
23
    /**
24
     * Indicates if loading of the provider is deferred.
25
     *
26
     * @var bool
27
     */
28
    protected $defer = false;
29
30
    /**
31
     * Where the route file lives, both inside the package and in the app (if overwritten).
32
     *
33
     * @var string
34
     */
35
    public $routeFilePath = '/routes/backpack/base.php';
36
37
    /**
38
     * Where custom routes can be written, and will be registered by Backpack.
39
     *
40
     * @var string
41
     */
42
    public $customRoutesFilePath = '/routes/backpack/custom.php';
43
44
    /**
45
     * Perform post-registration booting of services.
46
     *
47
     * @return void
48
     */
49
    public function boot(\Illuminate\Routing\Router $router)
0 ignored issues
show
Unused Code introduced by
The parameter $router is not used and could be removed.

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

Loading history...
50
    {
51
        $_SERVER['BACKPACK_BASE_VERSION'] = $this::VERSION;
52
        $customViewsFolder = resource_path('views/vendor/backpack/base');
53
54
        // LOAD THE VIEWS
55
        // - first the published views (in case they have any changes)
56
        if (file_exists(resource_path('views/vendor/backpack/base'))) {
57
            $this->loadViewsFrom($customViewsFolder, 'backpack');
58
        }
59
        // - then the stock views that come with the package, in case a published view might be missing
60
        $this->loadViewsFrom(realpath(__DIR__.'/resources/views'), 'backpack');
61
62
        $this->loadTranslationsFrom(realpath(__DIR__.'/resources/lang'), 'backpack');
63
64
        // use the vendor configuration file as fallback
65
        $this->mergeConfigFrom(
66
            __DIR__.'/config/backpack/base.php', 'backpack.base'
67
        );
68
69
        // add the root disk to filesystem configuration
70
        app()->config['filesystems.disks.'.config('backpack.base.root_disk_name')] = [
71
            'driver' => 'local',
72
            'root'   => base_path(),
73
        ];
74
75
        $this->allowCustomGuardDefinitionInRouteGroups();
76
        $this->addCustomAuthConfigurationValues();
77
        $this->registerMiddlewareGroup($this->app->router);
0 ignored issues
show
Bug introduced by
Accessing router on the interface Illuminate\Contracts\Foundation\Application suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
78
        $this->setupRoutes($this->app->router);
0 ignored issues
show
Bug introduced by
Accessing router on the interface Illuminate\Contracts\Foundation\Application suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
79
        $this->setupCustomRoutes($this->app->router);
0 ignored issues
show
Bug introduced by
Accessing router on the interface Illuminate\Contracts\Foundation\Application suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
80
        $this->publishFiles();
81
        $this->checkLicenseCodeExists();
82
    }
83
84
    /**
85
     * Load the Backpack helper methods, for convenience.
86
     */
87
    public function loadHelpers()
88
    {
89
        require_once __DIR__.'/helpers.php';
90
    }
91
92
    /**
93
     * In route groups you should be able to define 'guard' just like middleware,
94
     * namespace, prefix and what not. When specified, Auth will use that guard instead
95
     * of the default Laravel guard in config/auth.php.
96
     */
97
    public function allowCustomGuardDefinitionInRouteGroups()
98
    {
99
        $this->app['router']->matched(function (\Illuminate\Routing\Events\RouteMatched $e) {
100
            $route = $e->route;
101
            if (!array_has($route->getAction(), 'guard')) {
102
                return;
103
            }
104
            $routeGuard = array_get($route->getAction(), 'guard');
105
            $this->app['auth']->resolveUsersUsing(function ($guard = null) use ($routeGuard) {
0 ignored issues
show
Unused Code introduced by
The parameter $guard is not used and could be removed.

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

Loading history...
106
                return $this->app['auth']->guard($routeGuard)->user();
107
            });
108
            $this->app['auth']->setDefaultDriver($routeGuard);
109
        });
110
    }
111
112
    /**
113
     * Backpack login differs from the standard Laravel login.
114
     * As such, Backpack uses its own authentication provider, password broker and guard.
115
     *
116
     * This method adds those configuration values on top of whatever is in config/auth.php. Developers can overwrite the backpack provider, password broker or guard by adding a provider/broker/guard with the "backpack" name inside their config/auth.php file. Or they can use another provider/broker/guard entirely, by changing the corresponding value inside config/backpack/base.php
117
     */
118
    public function addCustomAuthConfigurationValues()
119
    {
120
        // add the backpack_users authentication provider to the configuration
121
        app()->config['auth.providers'] = app()->config['auth.providers'] +
122
        [
123
            'backpack' => [
124
                'driver'  => 'eloquent',
125
                'model'   => config('backpack.base.user_model_fqn'),
126
            ],
127
        ];
128
129
        // add the backpack_users password broker to the configuration
130
        app()->config['auth.passwords'] = app()->config['auth.passwords'] +
131
        [
132
            'backpack' => [
133
                'provider'  => 'backpack',
134
                'table'     => 'password_resets',
135
                'expire'    => 60,
136
            ],
137
        ];
138
139
        // add the backpack_users guard to the configuration
140
        app()->config['auth.guards'] = app()->config['auth.guards'] +
141
        [
142
            'backpack' => [
143
                'driver'   => 'session',
144
                'provider' => 'backpack',
145
            ],
146
        ];
147
    }
148
149
    /**
150
     * Define the routes for the application.
151
     *
152
     * @param \Illuminate\Routing\Router $router
153
     *
154
     * @return void
155
     */
156
    public function setupRoutes(Router $router)
0 ignored issues
show
Unused Code introduced by
The parameter $router is not used and could be removed.

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

Loading history...
157
    {
158
        // by default, use the routes file provided in vendor
159
        $routeFilePathInUse = __DIR__.$this->routeFilePath;
160
161
        // but if there's a file with the same name in routes/backpack, use that one
162
        if (file_exists(base_path().$this->routeFilePath)) {
163
            $routeFilePathInUse = base_path().$this->routeFilePath;
164
        }
165
166
        $this->loadRoutesFrom($routeFilePathInUse);
167
    }
168
169
    /**
170
     * Load custom routes file.
171
     *
172
     * @param \Illuminate\Routing\Router $router
173
     *
174
     * @return void
175
     */
176
    public function setupCustomRoutes(Router $router)
0 ignored issues
show
Unused Code introduced by
The parameter $router is not used and could be removed.

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

Loading history...
177
    {
178
        // if the custom routes file is published, register its routes
179
        if (file_exists(base_path().$this->customRoutesFilePath)) {
180
            $this->loadRoutesFrom(base_path().$this->customRoutesFilePath);
181
        }
182
    }
183
184
    /**
185
     * Register any package services.
186
     *
187
     * @return void
188
     */
189
    public function register()
190
    {
191
        // register the current package
192
        $this->app->bind('base', function ($app) {
193
            return new Base($app);
194
        });
195
196
        // register the helper functions
197
        $this->loadHelpers();
198
199
        // register its dependencies
200
        $this->app->register(\Jenssegers\Date\DateServiceProvider::class);
201
        $this->app->register(\Prologue\Alerts\AlertsServiceProvider::class);
202
        $this->app->register(\Creativeorange\Gravatar\GravatarServiceProvider::class);
203
204
        // register their aliases
205
        $loader = \Illuminate\Foundation\AliasLoader::getInstance();
206
        $loader->alias('Alert', \Prologue\Alerts\Facades\Alert::class);
207
        $loader->alias('Date', \Jenssegers\Date\Date::class);
208
        $loader->alias('Gravatar', \Creativeorange\Gravatar\Facades\Gravatar::class);
209
210
        // register the services that are only used for development
211
        if ($this->app->environment() == 'local') {
212
            if (class_exists('Laracasts\Generators\GeneratorsServiceProvider')) {
213
                $this->app->register('Laracasts\Generators\GeneratorsServiceProvider');
214
            }
215
            if (class_exists('Backpack\Generators\GeneratorsServiceProvider')) {
216
                $this->app->register('Backpack\Generators\GeneratorsServiceProvider');
217
            }
218
        }
219
220
        // register the artisan commands
221
        $this->commands($this->commands);
222
    }
223
224
    public function registerMiddlewareGroup(Router $router)
225
    {
226
        $middleware_key = config('backpack.base.middleware_key');
227
        $middleware_class = config('backpack.base.middleware_class');
228
229
        if (!is_array($middleware_class)) {
230
            $router->pushMiddlewareToGroup($middleware_key, $middleware_class);
231
232
            return;
233
        }
234
235
        foreach ($middleware_class as $middleware_class) {
236
            $router->pushMiddlewareToGroup($middleware_key, $middleware_class);
237
        }
238
    }
239
240
    public function publishFiles()
241
    {
242
        $error_views = [__DIR__.'/resources/error_views' => resource_path('views/errors')];
243
        $backpack_base_views = [__DIR__.'/resources/views' => resource_path('views/vendor/backpack/base')];
244
        $backpack_public_assets = [__DIR__.'/public' => public_path('vendor/backpack')];
245
        $backpack_lang_files = [__DIR__.'/resources/lang' => resource_path('lang/vendor/backpack')];
246
        $backpack_config_files = [__DIR__.'/config' => config_path()];
247
248
        // sidebar_content view, which is the only view most people need to overwrite
249
        $backpack_menu_contents_view = [
250
            __DIR__.'/resources/views/inc/sidebar_content.blade.php'      => resource_path('views/vendor/backpack/base/inc/sidebar_content.blade.php'),
251
            __DIR__.'/resources/views/inc/topbar_left_content.blade.php'  => resource_path('views/vendor/backpack/base/inc/topbar_left_content.blade.php'),
252
            __DIR__.'/resources/views/inc/topbar_right_content.blade.php' => resource_path('views/vendor/backpack/base/inc/topbar_right_content.blade.php'),
253
        ];
254
        $backpack_custom_routes_file = [__DIR__.$this->customRoutesFilePath => base_path($this->customRoutesFilePath)];
255
256
        // calculate the path from current directory to get the vendor path
257
        $vendorPath = dirname(__DIR__, 3);
258
        $adminlte_assets = [$vendorPath.'/almasaeed2010/adminlte' => public_path('vendor/adminlte')];
259
        $gravatar_assets = [$vendorPath.'/creativeorange/gravatar/config' => config_path()];
260
261
        // establish the minimum amount of files that need to be published, for Backpack to work; there are the files that will be published by the install command
262
        $minimum = array_merge(
263
            $error_views,
264
            // $backpack_base_views,
265
            $backpack_public_assets,
266
            // $backpack_lang_files,
267
            $backpack_config_files,
268
            $backpack_menu_contents_view,
269
            $backpack_custom_routes_file,
270
            $adminlte_assets,
271
            $gravatar_assets
272
        );
273
274
        // register all possible publish commands and assign tags to each
275
        $this->publishes($backpack_config_files, 'config');
276
        $this->publishes($backpack_lang_files, 'lang');
277
        $this->publishes($backpack_base_views, 'views');
278
        $this->publishes($backpack_menu_contents_view, 'menu_contents');
279
        $this->publishes($error_views, 'errors');
280
        $this->publishes($backpack_public_assets, 'public');
281
        $this->publishes($backpack_custom_routes_file, 'custom_routes');
282
        $this->publishes($adminlte_assets, 'adminlte');
283
        $this->publishes($gravatar_assets, 'gravatar');
284
        $this->publishes($minimum, 'minimum');
285
    }
286
287
    /**
288
     * Check to to see if a license code exists.
289
     * If it does not, throw a notification bubble.
290
     *
291
     * @return void
292
     */
293
    private function checkLicenseCodeExists()
294
    {
295
        if ($this->app->environment() != 'local' && !config('backpack.base.license_code')) {
296
            \Alert::add('warning', "<strong>You're using unlicensed software.</strong> Please ask your web developer to <a target='_blank' href='http://backpackforlaravel.com'>purchase a license code</a> to hide this message.");
297
        }
298
    }
299
}
300