Completed
Push — develop ( cc9a49...c1329f )
by Abdelrahman
09:49
created

FortServiceProvider   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 191
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 5
Bugs 0 Features 0
Metric Value
dl 0
loc 191
rs 10
c 5
b 0
f 0
wmc 17
lcom 1
cbo 5

7 Methods

Rating   Name   Duplication   Size   Complexity  
C register() 0 24 7
B boot() 0 63 4
A publishResources() 0 7 1
A registerCommands() 0 9 2
A attachRequestMacro() 0 8 1
A registerMenus() 0 4 1
A overrideMiddleware() 0 11 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cortex\Fort\Providers;
6
7
use Bouncer;
8
use Cortex\Fort\Models\Role;
9
use Cortex\Fort\Models\User;
10
use Illuminate\Http\Request;
11
use Illuminate\Routing\Router;
12
use Cortex\Fort\Models\Ability;
13
use Cortex\Fort\Models\Session;
14
use Cortex\Fort\Models\Socialite;
15
use Illuminate\Support\ServiceProvider;
16
use Cortex\Fort\Handlers\GenericHandler;
17
use Cortex\Fort\Http\Middleware\NoHttpCache;
18
use Cortex\Fort\Console\Commands\SeedCommand;
19
use Cortex\Fort\Http\Middleware\Authenticate;
20
use Cortex\Fort\Http\Middleware\Reauthenticate;
21
use Cortex\Fort\Console\Commands\InstallCommand;
22
use Cortex\Fort\Console\Commands\MigrateCommand;
23
use Cortex\Fort\Console\Commands\PublishCommand;
24
use Cortex\Fort\Console\Commands\RollbackCommand;
25
use Cortex\Fort\Http\Middleware\UpdateLastActivity;
26
use Illuminate\Database\Eloquent\Relations\Relation;
27
use Cortex\Fort\Http\Middleware\RedirectIfAuthenticated;
28
29
class FortServiceProvider extends ServiceProvider
30
{
31
    /**
32
     * The commands to be registered.
33
     *
34
     * @var array
35
     */
36
    protected $commands = [
37
        SeedCommand::class => 'command.cortex.fort.seed',
38
        InstallCommand::class => 'command.cortex.fort.install',
39
        MigrateCommand::class => 'command.cortex.fort.migrate',
40
        PublishCommand::class => 'command.cortex.fort.publish',
41
        RollbackCommand::class => 'command.cortex.fort.rollback',
42
    ];
43
44
    /**
45
     * Register any application services.
46
     *
47
     * This service provider is a great spot to register your various container
48
     * bindings with the application. As you can see, we are registering our
49
     * "Registrar" implementation here. You can add your own bindings too!
50
     *
51
     * @return void
52
     */
53
    public function register(): void
54
    {
55
        // Merge config
56
        $this->mergeConfigFrom(realpath(__DIR__.'/../../config/config.php'), 'cortex.fort');
57
58
        // Register console commands
59
        ! $this->app->runningInConsole() || $this->registerCommands();
60
61
        // Bind eloquent models to IoC container
62
        $this->app->singleton('cortex.fort.session', $sessionModel = $this->app['config']['cortex.fort.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...
63
        $sessionModel === Session::class || $this->app->alias('cortex.fort.session', Session::class);
64
65
        $this->app->singleton('cortex.fort.socialite', $socialiteModel = $this->app['config']['cortex.fort.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...
66
        $socialiteModel === Socialite::class || $this->app->alias('cortex.fort.socialite', Socialite::class);
67
68
        $this->app->singleton('cortex.fort.user', $userModel = $this->app['config']['cortex.fort.models.user']);
69
        $userModel === User::class || $this->app->alias('cortex.fort.user', User::class);
70
71
        $this->app->singleton('cortex.fort.role', $roleModel = $this->app['config']['cortex.fort.models.role']);
72
        $roleModel === Role::class || $this->app->alias('cortex.fort.role', Role::class);
73
74
        $this->app->singleton('cortex.fort.ability', $abilityModel = $this->app['config']['cortex.fort.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...
75
        $abilityModel === Ability::class || $this->app->alias('cortex.fort.ability', Ability::class);
76
    }
77
78
    /**
79
     * Bootstrap any application services.
80
     *
81
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
82
     *
83
     * @return void
84
     */
85
    public function boot(Router $router): void
86
    {
87
        // Attach request macro
88
        $this->attachRequestMacro();
89
90
        // Map bouncer models
91
        Bouncer::useUserModel(config('cortex.fort.models.user'));
92
        Bouncer::useRoleModel(config('cortex.fort.models.role'));
93
        Bouncer::useAbilityModel(config('cortex.fort.models.ability'));
94
95
        // Map bouncer tables (users, roles, abilities tables are set through their models)
96
        Bouncer::tables([
97
            'permissions' => config('cortex.fort.tables.permissions'),
98
            'assigned_roles' => config('cortex.fort.tables.assigned_roles'),
99
        ]);
100
101
        // Bind route models and constrains
102
        $router->pattern('role', '[0-9]+');
103
        $router->pattern('ability', '[0-9]+');
104
        $router->pattern('user', '[a-zA-Z0-9_-]+');
105
        $router->pattern('session', '[a-zA-Z0-9]+');
106
        $router->model('role', config('cortex.fort.models.role'));
107
        $router->model('user', config('cortex.fort.models.user'));
108
        $router->model('ability', config('cortex.fort.models.ability'));
109
        $router->model('session', config('cortex.fort.models.session'));
110
111
        // Map relations
112
        Relation::morphMap([
113
            'user' => config('cortex.fort.models.user'),
114
            'role' => config('cortex.fort.models.role'),
115
            'ability' => config('cortex.fort.models.ability'),
116
        ]);
117
118
        // Load resources
119
        require __DIR__.'/../../routes/breadcrumbs.php';
120
        $this->loadRoutesFrom(__DIR__.'/../../routes/web.php');
121
        $this->loadViewsFrom(__DIR__.'/../../resources/views', 'cortex/fort');
122
        $this->loadTranslationsFrom(__DIR__.'/../../resources/lang', 'cortex/fort');
123
        ! $this->app->runningInConsole() || $this->loadMigrationsFrom(__DIR__.'/../../database/migrations');
124
        $this->app->afterResolving('blade.compiler', function () {
125
            require __DIR__.'/../../routes/menus.php';
126
        });
127
128
        // Publish Resources
129
        ! $this->app->runningInConsole() || $this->publishResources();
130
131
        // Register event handlers
132
        $this->app['events']->subscribe(GenericHandler::class);
133
134
        // Register attributes entities
135
        ! app()->bound('rinvex.attributes.entities') || app('rinvex.attributes.entities')->push('user');
136
137
        // Override middlware
138
        $this->overrideMiddleware($router);
139
140
        // Register menus
141
        $this->registerMenus();
142
143
        // Share current user instance with all views
144
        $this->app['view']->composer('*', function ($view) {
145
            $view->with('currentUser', auth()->user());
0 ignored issues
show
Bug introduced by
The method user does only exist in Illuminate\Contracts\Auth\Guard, but not in Illuminate\Contracts\Auth\Factory.

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...
146
        });
147
    }
148
149
    /**
150
     * Publish resources.
151
     *
152
     * @return void
153
     */
154
    protected function publishResources(): void
155
    {
156
        $this->publishes([realpath(__DIR__.'/../../config/config.php') => config_path('cortex.fort.php')], 'cortex-fort-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...
157
        $this->publishes([realpath(__DIR__.'/../../database/migrations') => database_path('migrations')], 'cortex-fort-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...
158
        $this->publishes([realpath(__DIR__.'/../../resources/lang') => resource_path('lang/vendor/cortex/fort')], 'cortex-fort-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...
159
        $this->publishes([realpath(__DIR__.'/../../resources/views') => resource_path('views/vendor/cortex/fort')], 'cortex-fort-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...
160
    }
161
162
    /**
163
     * Register console commands.
164
     *
165
     * @return void
166
     */
167
    protected function registerCommands(): void
168
    {
169
        // Register artisan commands
170
        foreach ($this->commands as $key => $value) {
171
            $this->app->singleton($value, $key);
172
        }
173
174
        $this->commands(array_values($this->commands));
175
    }
176
177
    /**
178
     * Register console commands.
179
     *
180
     * @return void
181
     */
182
    protected function attachRequestMacro(): void
183
    {
184
        Request::macro('attemptUser', function (string $guard = null) {
185
            $twofactor = $this->session()->get('cortex.fort.twofactor');
0 ignored issues
show
Bug introduced by
The method session() does not seem to exist on object<Cortex\Fort\Providers\FortServiceProvider>.

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...
186
187
            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...
188
        });
189
    }
190
191
    /**
192
     * Register menus.
193
     *
194
     * @return void
195
     */
196
    protected function registerMenus(): void
197
    {
198
        $this->app['rinvex.menus.presenters']->put('account.sidebar', \Cortex\Fort\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...
199
    }
200
201
    /**
202
     * Override middleware.
203
     *
204
     * @param \Illuminate\Routing\Router $router
205
     *
206
     * @return void
207
     */
208
    protected function overrideMiddleware(Router $router): void
209
    {
210
        // Append middleware to the 'web' middlware group
211
        $router->pushMiddlewareToGroup('web', UpdateLastActivity::class);
212
213
        // Override route middleware on the fly
214
        $router->aliasMiddleware('auth', Authenticate::class);
215
        $router->aliasMiddleware('nohttpcache', NoHttpCache::class);
216
        $router->aliasMiddleware('reauthenticate', Reauthenticate::class);
217
        $router->aliasMiddleware('guest', RedirectIfAuthenticated::class);
218
    }
219
}
220