Completed
Push — master ( 20a6e3...887da8 )
by Abdelrahman
04:09 queued 02:12
created

AuthServiceProvider   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 212
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 24
lcom 1
cbo 5
dl 0
loc 212
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
D register() 0 34 10
B boot() 0 76 8
A publishResources() 0 7 1
A registerCommands() 0 9 2
A attachRequestMacro() 0 8 1
A registerMenus() 0 4 1
A overrideMiddleware() 0 9 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cortex\Auth\Providers;
6
7
use Bouncer;
8
use Cortex\Auth\Models\Role;
9
use Illuminate\Http\Request;
10
use Cortex\Auth\Models\Admin;
11
use Cortex\Auth\Models\Member;
12
use Illuminate\Routing\Router;
13
use Cortex\Auth\Models\Ability;
14
use Cortex\Auth\Models\Manager;
15
use Cortex\Auth\Models\Session;
16
use Cortex\Auth\Models\Guardian;
17
use Cortex\Auth\Models\Socialite;
18
use Illuminate\Support\ServiceProvider;
19
use Cortex\Auth\Handlers\GenericHandler;
20
use Cortex\Auth\Console\Commands\SeedCommand;
21
use Cortex\Auth\Http\Middleware\Reauthenticate;
22
use Cortex\Auth\Console\Commands\InstallCommand;
23
use Cortex\Auth\Console\Commands\MigrateCommand;
24
use Cortex\Auth\Console\Commands\PublishCommand;
25
use Cortex\Auth\Console\Commands\RollbackCommand;
26
use Cortex\Auth\Http\Middleware\UpdateLastActivity;
27
use Illuminate\Database\Eloquent\Relations\Relation;
28
use Cortex\Auth\Http\Middleware\RedirectIfAuthenticated;
29
30
class AuthServiceProvider extends ServiceProvider
31
{
32
    /**
33
     * The commands to be registered.
34
     *
35
     * @var array
36
     */
37
    protected $commands = [
38
        SeedCommand::class => 'command.cortex.auth.seed',
39
        InstallCommand::class => 'command.cortex.auth.install',
40
        MigrateCommand::class => 'command.cortex.auth.migrate',
41
        PublishCommand::class => 'command.cortex.auth.publish',
42
        RollbackCommand::class => 'command.cortex.auth.rollback',
43
    ];
44
45
    /**
46
     * Register any application services.
47
     *
48
     * This service provider is a great spot to register your various container
49
     * bindings with the application. As you can see, we are registering our
50
     * "Registrar" implementation here. You can add your own bindings too!
51
     *
52
     * @return void
53
     */
54
    public function register(): void
55
    {
56
        // Merge config
57
        $this->app['config']->set('auth.model', config('cortex.auth.models.member'));
58
        $this->mergeConfigFrom(realpath(__DIR__.'/../../config/config.php'), 'cortex.auth');
59
60
        // Register console commands
61
        ! $this->app->runningInConsole() || $this->registerCommands();
62
63
        // Bind eloquent models to IoC container
64
        $this->app->singleton('cortex.auth.session', $sessionModel = $this->app['config']['cortex.auth.models.session']);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
65
        $sessionModel === Session::class || $this->app->alias('cortex.auth.session', Session::class);
66
67
        $this->app->singleton('cortex.auth.socialite', $socialiteModel = $this->app['config']['cortex.auth.models.socialite']);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
68
        $socialiteModel === Socialite::class || $this->app->alias('cortex.auth.socialite', Socialite::class);
69
70
        $this->app->singleton('cortex.auth.admin', $adminModel = $this->app['config']['cortex.auth.models.admin']);
71
        $adminModel === Admin::class || $this->app->alias('cortex.auth.admin', Admin::class);
72
73
        $this->app->singleton('cortex.auth.member', $memberModel = $this->app['config']['cortex.auth.models.member']);
74
        $memberModel === Member::class || $this->app->alias('cortex.auth.member', Member::class);
75
76
        $this->app->singleton('cortex.auth.manager', $managerModel = $this->app['config']['cortex.auth.models.manager']);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
77
        $managerModel === Manager::class || $this->app->alias('cortex.auth.manager', Manager::class);
78
79
        $this->app->singleton('cortex.auth.guardian', $guardianModel = $this->app['config']['cortex.auth.models.guardian']);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 124 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
80
        $guardianModel === Guardian::class || $this->app->alias('cortex.auth.guardian', Guardian::class);
81
82
        $this->app->singleton('cortex.auth.role', $roleModel = $this->app['config']['cortex.auth.models.role']);
83
        $roleModel === Role::class || $this->app->alias('cortex.auth.role', Role::class);
84
85
        $this->app->singleton('cortex.auth.ability', $abilityModel = $this->app['config']['cortex.auth.models.ability']);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
86
        $abilityModel === Ability::class || $this->app->alias('cortex.auth.ability', Ability::class);
87
    }
88
89
    /**
90
     * Bootstrap any application services.
91
     *
92
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
93
     *
94
     * @return void
95
     */
96
    public function boot(Router $router): void
97
    {
98
        // Attach request macro
99
        $this->attachRequestMacro();
100
101
        // Map bouncer models
102
        Bouncer::useRoleModel(config('cortex.auth.models.role'));
103
        Bouncer::useAbilityModel(config('cortex.auth.models.ability'));
104
105
        // Map bouncer tables (users, roles, abilities tables are set through their models)
106
        Bouncer::tables([
107
            'permissions' => config('cortex.auth.tables.permissions'),
108
            'assigned_roles' => config('cortex.auth.tables.assigned_roles'),
109
        ]);
110
111
        // Bind route models and constrains
112
        $router->pattern('role', '[a-zA-Z0-9-]+');
113
        $router->pattern('ability', '[a-zA-Z0-9-]+');
114
        $router->pattern('session', '[a-zA-Z0-9-]+');
115
        $router->pattern('admin', '[a-zA-Z0-9-]+');
116
        $router->pattern('member', '[a-zA-Z0-9-]+');
117
        $router->pattern('manager', '[a-zA-Z0-9-]+');
118
        $router->model('role', config('cortex.auth.models.role'));
119
        $router->model('admin', config('cortex.auth.models.admin'));
120
        $router->model('member', config('cortex.auth.models.member'));
121
        $router->model('manager', config('cortex.auth.models.manager'));
122
        $router->model('guardian', config('cortex.auth.models.guardian'));
123
        $router->model('ability', config('cortex.auth.models.ability'));
124
        $router->model('session', config('cortex.auth.models.session'));
125
126
        // Map relations
127
        Relation::morphMap([
128
            'role' => config('cortex.auth.models.role'),
129
            'admin' => config('cortex.auth.models.admin'),
130
            'member' => config('cortex.auth.models.member'),
131
            'manager' => config('cortex.auth.models.manager'),
132
            'guardian' => config('cortex.auth.models.guardian'),
133
            'ability' => config('cortex.auth.models.ability'),
134
        ]);
135
136
        // Load resources
137
        require __DIR__.'/../../routes/breadcrumbs/adminarea.php';
138
        $this->loadRoutesFrom(__DIR__.'/../../routes/web/adminarea.php');
139
        $this->loadViewsFrom(__DIR__.'/../../resources/views', 'cortex/auth');
140
        $this->loadTranslationsFrom(__DIR__.'/../../resources/lang', 'cortex/auth');
141
        ! $this->app->runningInConsole() || $this->loadMigrationsFrom(__DIR__.'/../../database/migrations');
142
        $this->app->runningInConsole() || $this->app->afterResolving('blade.compiler', function () {
143
            require __DIR__.'/../../routes/menus/managerarea.php';
144
            require __DIR__.'/../../routes/menus/tenantarea.php';
145
            require __DIR__.'/../../routes/menus/adminarea.php';
146
            require __DIR__.'/../../routes/menus/frontarea.php';
147
        });
148
149
        // Publish Resources
150
        ! $this->app->runningInConsole() || $this->publishResources();
151
152
        // Register event handlers
153
        $this->app['events']->subscribe(GenericHandler::class);
154
155
        // Register attributes entities
156
        ! app()->bound('rinvex.attributes.entities') || app('rinvex.attributes.entities')->push('admin');
157
        ! app()->bound('rinvex.attributes.entities') || app('rinvex.attributes.entities')->push('member');
158
        ! app()->bound('rinvex.attributes.entities') || app('rinvex.attributes.entities')->push('manager');
159
160
        // Override middlware
161
        $this->overrideMiddleware($router);
162
163
        // Register menus
164
        $this->registerMenus();
165
166
        // Share current user instance with all views
167
        $this->app['view']->composer('*', function ($view) {
168
            ! config('rinvex.tenants.active') || $view->with('currentTenant', config('rinvex.tenants.active'));
169
            $view->with('currentUser', auth()->guard(request()->route('guard'))->user());
0 ignored issues
show
Bug introduced by
The method guard does only exist in Illuminate\Contracts\Auth\Factory, but not in Illuminate\Contracts\Auth\Guard.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
170
        });
171
    }
172
173
    /**
174
     * Publish resources.
175
     *
176
     * @return void
177
     */
178
    protected function publishResources(): void
179
    {
180
        $this->publishes([realpath(__DIR__.'/../../config/config.php') => config_path('cortex.auth.php')], 'cortex-auth-config');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 129 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
181
        $this->publishes([realpath(__DIR__.'/../../database/migrations') => database_path('migrations')], 'cortex-auth-migrations');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 132 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
182
        $this->publishes([realpath(__DIR__.'/../../resources/lang') => resource_path('lang/vendor/cortex/auth')], 'cortex-auth-lang');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 134 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
183
        $this->publishes([realpath(__DIR__.'/../../resources/views') => resource_path('views/vendor/cortex/auth')], 'cortex-auth-views');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 137 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
184
    }
185
186
    /**
187
     * Register console commands.
188
     *
189
     * @return void
190
     */
191
    protected function registerCommands(): void
192
    {
193
        // Register artisan commands
194
        foreach ($this->commands as $key => $value) {
195
            $this->app->singleton($value, $key);
196
        }
197
198
        $this->commands(array_values($this->commands));
199
    }
200
201
    /**
202
     * Register console commands.
203
     *
204
     * @return void
205
     */
206
    protected function attachRequestMacro(): void
207
    {
208
        Request::macro('attemptUser', function (string $guard = null) {
209
            $twofactor = $this->session()->get('cortex.auth.twofactor');
0 ignored issues
show
Bug introduced by
The method session() does not seem to exist on object<Cortex\Auth\Providers\AuthServiceProvider>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
210
211
            return auth()->guard($guard)->getProvider()->retrieveById($twofactor['user_id']);
0 ignored issues
show
Bug introduced by
The method guard does only exist in Illuminate\Contracts\Auth\Factory, but not in Illuminate\Contracts\Auth\Guard.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
212
        });
213
    }
214
215
    /**
216
     * Register menus.
217
     *
218
     * @return void
219
     */
220
    protected function registerMenus(): void
221
    {
222
        $this->app['rinvex.menus.presenters']->put('account.sidebar', \Cortex\Auth\Presenters\AccountSidebarMenuPresenter::class);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 130 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
223
    }
224
225
    /**
226
     * Override middleware.
227
     *
228
     * @param \Illuminate\Routing\Router $router
229
     *
230
     * @return void
231
     */
232
    protected function overrideMiddleware(Router $router): void
233
    {
234
        // Append middleware to the 'web' middlware group
235
        $router->pushMiddlewareToGroup('web', UpdateLastActivity::class);
236
237
        // Override route middleware on the fly
238
        $router->aliasMiddleware('reauthenticate', Reauthenticate::class);
239
        $router->aliasMiddleware('guest', RedirectIfAuthenticated::class);
240
    }
241
}
242