Completed
Push — develop ( 9664f4...8505c4 )
by Abdelrahman
06:05
created

FortServiceProvider::overrideSessionGuard()   B

Complexity

Conditions 4
Paths 1

Size

Total Lines 26
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 1
nop 0
dl 0
loc 26
rs 8.5806
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A FortServiceProvider::registerPasswordBroker() 0 10 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Rinvex\Fort\Providers;
6
7
use Rinvex\Fort\Models\Role;
8
use Rinvex\Fort\Models\User;
9
use Illuminate\Routing\Router;
10
use Rinvex\Fort\Models\Ability;
11
use Rinvex\Fort\Models\Session;
12
use Rinvex\Fort\Models\Socialite;
13
use Rinvex\Fort\Services\AccessGate;
14
use Illuminate\Support\ServiceProvider;
15
use Rinvex\Fort\Handlers\GenericHandler;
16
use Illuminate\Support\Facades\Validator;
17
use Rinvex\Fort\Http\Middleware\Abilities;
18
use Illuminate\View\Compilers\BladeCompiler;
19
use Rinvex\Fort\Http\Middleware\NoHttpCache;
20
use Rinvex\Fort\Http\Middleware\Authenticate;
21
use Rinvex\Fort\Console\Commands\MigrateCommand;
22
use Rinvex\Fort\Console\Commands\PublishCommand;
23
use Rinvex\Fort\Console\Commands\RollbackCommand;
24
use Rinvex\Fort\Http\Middleware\UpdateLastActivity;
25
use Rinvex\Fort\Services\PasswordResetBrokerManager;
26
use Rinvex\Fort\Http\Middleware\RedirectIfAuthenticated;
27
use Rinvex\Fort\Services\EmailVerificationBrokerManager;
28
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
29
30
class FortServiceProvider extends ServiceProvider
31
{
32
    /**
33
     * The commands to be registered.
34
     *
35
     * @var array
36
     */
37
    protected $commands = [
38
        MigrateCommand::class => 'command.rinvex.fort.migrate',
39
        PublishCommand::class => 'command.rinvex.fort.publish',
40
        RollbackCommand::class => 'command.rinvex.fort.rollback',
41
    ];
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function register()
47
    {
48
        // Register bindings
49
        $this->registerPasswordBroker();
50
        $this->registerVerificationBroker();
51
52
        // Register console commands
53
        ! $this->app->runningInConsole() || $this->registerCommands();
54
55
        // Merge config
56
        $this->mergeConfigFrom(realpath(__DIR__.'/../../config/config.php'), 'rinvex.fort');
57
58
        // Register Access Gate Binding
59
        $this->registerAccessGate();
60
61
        // Bind eloquent models to IoC container
62
        $this->app->singleton('rinvex.fort.role', function ($app) {
63
            return new $app['config']['rinvex.fort.models.role']();
64
        });
65
        $this->app->alias('rinvex.fort.role', Role::class);
66
67
        $this->app->singleton('rinvex.fort.ability', function ($app) {
68
            return new $app['config']['rinvex.fort.models.ability']();
69
        });
70
        $this->app->alias('rinvex.fort.ability', Ability::class);
71
72
        $this->app->singleton('rinvex.fort.session', function ($app) {
73
            return new $app['config']['rinvex.fort.models.session']();
74
        });
75
        $this->app->alias('rinvex.fort.session', Session::class);
76
77
        $this->app->singleton('rinvex.fort.socialite', function ($app) {
78
            return new $app['config']['rinvex.fort.models.socialite']();
79
        });
80
        $this->app->alias('rinvex.fort.socialite', Socialite::class);
81
82
        $this->app->singleton('rinvex.fort.user', function ($app) {
83
            return new $app['config']['auth.providers.'.$app['config']['auth.guards.'.$app['config']['auth.defaults.guard'].'.provider'].'.model']();
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 149 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...
84
        });
85
        $this->app->alias('rinvex.fort.user', User::class);
86
    }
87
88
    /**
89
     * Register the access gate service.
90
     *
91
     * @return void
92
     */
93
    protected function registerAccessGate(): void
94
    {
95
        $this->app->singleton(GateContract::class, function ($app) {
96
            return new AccessGate($app, function () use ($app) {
97
                return call_user_func($app['auth']->userResolver());
98
            });
99
        });
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105
    public function boot(Router $router)
106
    {
107
        // Add country validation rule
108
        Validator::extend('country', function ($attribute, $value) {
109
            return in_array($value, array_keys(countries()));
110
        }, 'Country MUST be valid!');
111
112
        // Add langauge validation rule
113
        Validator::extend('language', function ($attribute, $value) {
114
            return in_array($value, array_keys(languages()));
115
        }, 'Language MUST be valid!');
116
117
        if (config('rinvex.fort.boot.override_middleware')) {
118
            // Override middlware
119
            $this->overrideMiddleware($router);
120
        }
121
122
        // Publish resources
123
        ! $this->app->runningInConsole() || $this->publishResources();
124
125
        // Register event handlers
126
        $this->app['events']->subscribe(GenericHandler::class);
127
128
        // Share current user instance with all views
129
        $this->app['view']->composer('*', function ($view) {
130
            $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...
131
        });
132
133
        // Register blade extensions
134
        $this->registerBladeExtensions();
135
    }
136
137
    /**
138
     * Publish resources.
139
     *
140
     * @return void
141
     */
142
    protected function publishResources(): void
143
    {
144
        $this->publishes([realpath(__DIR__.'/../../config/config.php') => config_path('rinvex.fort.php')], 'rinvex-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...
145
        $this->publishes([realpath(__DIR__.'/../../database/migrations') => database_path('migrations')], 'rinvex-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...
146
    }
147
148
    /**
149
     * Override middleware.
150
     *
151
     * @param \Illuminate\Routing\Router $router
152
     *
153
     * @return void
154
     */
155
    protected function overrideMiddleware(Router $router): void
156
    {
157
        // Append middleware to the 'web' middlware group
158
        $router->pushMiddlewareToGroup('web', Abilities::class);
159
        $router->pushMiddlewareToGroup('web', UpdateLastActivity::class);
160
161
        // Override route middleware on the fly
162
        $router->aliasMiddleware('auth', Authenticate::class);
163
        $router->aliasMiddleware('nohttpcache', NoHttpCache::class);
164
        $router->aliasMiddleware('guest', RedirectIfAuthenticated::class);
165
    }
166
167
    /**
168
     * Register the password broker.
169
     *
170
     * @return void
171
     */
172
    protected function registerPasswordBroker(): void
173
    {
174
        $this->app->singleton('auth.password', function ($app) {
175
            return new PasswordResetBrokerManager($app);
176
        });
177
178
        $this->app->bind('auth.password.broker', function ($app) {
179
            return $app->make('auth.password')->broker();
180
        });
181
    }
182
183
    /**
184
     * Register the verification broker.
185
     *
186
     * @return void
187
     */
188
    protected function registerVerificationBroker(): void
189
    {
190
        $this->app->singleton('rinvex.fort.emailverification', function ($app) {
191
            return new EmailVerificationBrokerManager($app);
192
        });
193
194
        $this->app->bind('rinvex.fort.emailverification.broker', function ($app) {
195
            return $app->make('rinvex.fort.emailverification')->broker();
196
        });
197
    }
198
199
    /**
200
     * Register the blade extensions.
201
     *
202
     * @return void
203
     */
204
    protected function registerBladeExtensions(): void
205
    {
206
        $this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) {
207
208
            // @hasAnyRoles(['writer', 'editor'])
209
            $bladeCompiler->directive('hasAnyRoles', function ($expression) {
210
                return "<?php if(auth()->user()->hasAnyRoles({$expression})): ?>";
211
            });
212
            $bladeCompiler->directive('endHasAnyRoles', function () {
213
                return '<?php endif; ?>';
214
            });
215
216
            // @hasAllRoles(['writer', 'editor'])
217
            $bladeCompiler->directive('hasAllRoles', function ($expression) {
218
                return "<?php if(auth()->user()->hasAllRoles({$expression})): ?>";
219
            });
220
            $bladeCompiler->directive('endHasAllRoles', function () {
221
                return '<?php endif; ?>';
222
            });
223
        });
224
    }
225
226
    /**
227
     * Register console commands.
228
     *
229
     * @return void
230
     */
231
    protected function registerCommands(): void
232
    {
233
        // Register artisan commands
234
        foreach ($this->commands as $key => $value) {
235
            $this->app->singleton($value, function ($app) use ($key) {
0 ignored issues
show
Unused Code introduced by
The parameter $app 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...
236
                return new $key();
237
            });
238
        }
239
240
        $this->commands(array_values($this->commands));
241
    }
242
}
243