Completed
Push — master ( af85d6...66f137 )
by Abdelrahman
03:41
created

FortServiceProvider::addCustomUserProvider()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * NOTICE OF LICENSE
5
 *
6
 * Part of the Rinvex Fort Package.
7
 *
8
 * This source file is subject to The MIT License (MIT)
9
 * that is bundled with this package in the LICENSE file.
10
 *
11
 * Package: Rinvex Fort Package
12
 * License: The MIT License (MIT)
13
 * Link:    https://rinvex.com
14
 */
15
16
namespace Rinvex\Fort\Providers;
17
18
use Illuminate\Routing\Router;
19
use Illuminate\Support\Facades\Auth;
20
use Rinvex\Fort\Guards\SessionGuard;
21
use Rinvex\Fort\Services\BrokerManager;
22
use Rinvex\Fort\Listeners\FortEventListener;
23
use Illuminate\View\Compilers\BladeCompiler;
24
use Rinvex\Fort\Repositories\UserRepository;
25
use Rinvex\Fort\Repositories\RoleRepository;
26
use Laravel\Socialite\SocialiteServiceProvider;
27
use Rinvex\Fort\Repositories\AbilityRepository;
28
use Rinvex\Support\Providers\BaseServiceProvider;
29
use Rinvex\Fort\Repositories\PersistenceRepository;
30
31
class FortServiceProvider extends BaseServiceProvider
32
{
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function register()
37
    {
38
        // Merge config
39
        $this->mergeConfigFrom(realpath(__DIR__.'/../../config/config.php'), 'rinvex.fort');
40
41
        // Register bindings
42
        $this->registerRepositories();
43
        $this->registerBrokerManagers();
44
        $this->registerBladeExtensions();
45
46
        // Register the event listener
47
        $this->app->bind('rinvex.fort.listener', FortEventListener::class);
48
49
        // Register the Socialite Service Provider
50
        $this->app->register(SocialiteServiceProvider::class);
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function boot(Router $router)
57
    {
58
        // Publish Resources
59
        $this->publishResources();
60
61
        // Add middleware group on the fly
62
        $router->middlewareGroup('rinvex.fort.backend', [
63
            \App\Http\Middleware\EncryptCookies::class,
64
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
65
            \Illuminate\Session\Middleware\StartSession::class,
66
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
67
            \App\Http\Middleware\VerifyCsrfToken::class,
68
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
69
            \Rinvex\Fort\Http\Middleware\Abilities::class,
70
        ]);
71
72
        // Override route middleware on the fly
73
        $router->middleware('auth', \Rinvex\Fort\Http\Middleware\Authenticate::class);
74
        $router->middleware('guest', \Rinvex\Fort\Http\Middleware\RedirectIfAuthenticated::class);
75
76
        // Load routes
77
        $this->loadRoutes($router);
78
79
        // Override exception handler
80
        $this->app->singleton(
81
            \Illuminate\Contracts\Debug\ExceptionHandler::class,
82
            \Rinvex\Fort\Exceptions\Handler::class
83
        );
84
85
        // Load views
86
        $this->loadViewsFrom(__DIR__.'/../../resources/views', 'rinvex/fort');
87
88
        // Load language phrases
89
        $this->loadTranslationsFrom(__DIR__.'/../../resources/lang', 'rinvex/fort');
90
91
        // Load migrations
92
        $this->loadMigrationsFrom(__DIR__.'/../../database/migrations');
93
94
        // Subscribe the registered event listener
95
        $this->app['events']->subscribe('rinvex.fort.listener');
96
97
        // Override user provider
98
        $this->overrideUserProvider();
99
100
        // Override session guard
101
        $this->overrideSessionGuard();
102
103
        // Share current user instance with all views
104
        $this->app['view']->composer('*', function ($view) {
105
            $view->with('currentUser', Auth::user());
106
        });
107
    }
108
109
    /**
110
     * Bind the repositories into the IoC.
111
     *
112
     * @return void
113
     */
114
    protected function registerRepositories()
115
    {
116
        $this->bindAndAlias('rinvex.fort.role', RoleRepository::class);
117
        $this->bindAndAlias('rinvex.fort.user', UserRepository::class);
118
        $this->bindAndAlias('rinvex.fort.ability', AbilityRepository::class);
119
        $this->bindAndAlias('rinvex.fort.persistence', PersistenceRepository::class);
120
    }
121
122
    /**
123
     * Register the broker managers.
124
     *
125
     * @return void
126
     */
127
    protected function registerBrokerManagers()
128
    {
129
        // Register reset broker manager
130
        $this->app->singleton('rinvex.fort.resetter', function ($app) {
131
            return new BrokerManager($app, 'reset');
132
        });
133
134
        // Register verification broker manager
135
        $this->app->singleton('rinvex.fort.verifier', function ($app) {
136
            return new BrokerManager($app, 'verification');
137
        });
138
    }
139
140
    /**
141
     * Register the blade extensions.
142
     *
143
     * @return void
144
     */
145
    protected function registerBladeExtensions()
146
    {
147
        $this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) {
148
149
            // @role('writer')
150
            $bladeCompiler->directive('role', function ($model, $role) {
151
                return "<?php if(auth()->check() && app('rinvex.fort.user')->hasRole({$model}, {$role})): ?>";
2 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $model instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $role instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
152
            });
153
            $bladeCompiler->directive('endrole', function () {
154
                return '<?php endif; ?>';
155
            });
156
157
            // @hasrole('writer')
158
            $bladeCompiler->directive('hasrole', function ($model, $role) {
159
                return "<?php if(auth()->check() && app('rinvex.fort.user')->hasRole({$model}, {$role})): ?>";
2 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $model instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $role instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
160
            });
161
            $bladeCompiler->directive('endhasrole', function () {
162
                return '<?php endif; ?>';
163
            });
164
165
            // @hasanyrole(['writer', 'editor'])
166
            $bladeCompiler->directive('hasanyrole', function ($model, $roles) {
167
                return "<?php if(auth()->check() && app('rinvex.fort.user')->hasAnyRole({$model}, {$roles})): ?>";
2 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $model instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $roles instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
168
            });
169
            $bladeCompiler->directive('endhasanyrole', function () {
170
                return '<?php endif; ?>';
171
            });
172
173
            // @hasallroles(['writer', 'editor'])
174
            $bladeCompiler->directive('hasallroles', function ($model, $roles) {
175
                return "<?php if(auth()->check() && app('rinvex.fort.user')->hasAllRoles({$model}, {$roles})): ?>";
2 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $model instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $roles instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
176
            });
177
            $bladeCompiler->directive('endhasallroles', function () {
178
                return '<?php endif; ?>';
179
            });
180
        });
181
    }
182
183
    /**
184
     * Publish resources.
185
     *
186
     * @return void
187
     */
188
    protected function publishResources()
189
    {
190
        // Publish config
191
        $this->publishes([
192
            realpath(__DIR__.'/../../config/config.php') => config_path('rinvex.fort.php'),
193
        ], 'config');
194
195
        // Publish migrations
196
        $this->publishes([
197
            realpath(__DIR__.'/../../database/migrations') => database_path('migrations'),
198
        ], 'migrations');
199
200
        // Publish language phrases
201
        $this->publishes([
202
            realpath(__DIR__.'/../../resources/lang') => resource_path('lang/vendor/rinvex/fort'),
203
        ], 'lang');
204
205
        // Publish views
206
        $this->publishes([
207
            realpath(__DIR__.'/../../resources/views') => resource_path('views/vendor/rinvex/fort'),
208
        ], 'views');
209
    }
210
211
    /**
212
     * Load the routes.
213
     *
214
     * @param \Illuminate\Routing\Router $router
215
     *
216
     * @return void
217
     */
218
    public function loadRoutes(Router $router)
219
    {
220
        // Load routes
221
        if ($this->app->routesAreCached()) {
222
            $this->app->booted(function () {
223
                require $this->app->getCachedRoutesPath();
224
            });
225
        } else {
226
            // Load the application routes
227
            require __DIR__.'/../../routes/web.backend.php';
228
            require __DIR__.'/../../routes/web.frontend.php';
229
230
            $this->app->booted(function () use ($router) {
231
                $router->getRoutes()->refreshNameLookups();
232
            });
233
        }
234
    }
235
236
    /**
237
     * Add custom user provider.
238
     *
239
     * @return void
240
     */
241
    protected function overrideUserProvider()
242
    {
243
        $this->app['auth']->provider('eloquent', function ($app, array $config) {
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...
Unused Code introduced by
The parameter $config 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...
244
            // Return an instance of Rinvex\Fort\Contracts\UserRepositoryContract
245
            return $this->app['rinvex.fort.user'];
246
        });
247
    }
248
249
    /**
250
     * Add custom session guard.
251
     *
252
     * @return void
253
     */
254
    protected function overrideSessionGuard()
255
    {
256
        // Add custom session guard
257
        $this->app['auth']->extend('session', function ($app, $name, array $config) {
258
            $provider = $app['auth']->createUserProvider($config['provider']);
259
260
            $guard = new SessionGuard($name, $provider, $app['session.store'], $app['request']);
261
262
            // When using the remember me functionality of the authentication services we
263
            // will need to be set the encryption instance of the guard, which allows
264
            // secure, encrypted cookie values to get generated for those cookies.
265
            if (method_exists($guard, 'setCookieJar')) {
266
                $guard->setCookieJar($this->app['cookie']);
267
            }
268
269
            if (method_exists($guard, 'setDispatcher')) {
270
                $guard->setDispatcher($this->app['events']);
271
            }
272
273
            if (method_exists($guard, 'setRequest')) {
274
                $guard->setRequest($this->app->refresh('request', $guard, 'setRequest'));
275
            }
276
277
            return $guard;
278
        });
279
    }
280
}
281