Completed
Push — master ( b739db...92d607 )
by Abdelrahman
02:42
created

FortServiceProvider::addCustomSessionGuard()   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
<?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
        // Load routes
62
        $this->loadRoutes($router);
63
64
        // Load views
65
        $this->loadViewsFrom(__DIR__.'/../../resources/views', 'rinvex.fort');
66
67
        // Load language phrases
68
        $this->loadTranslationsFrom(__DIR__.'/../../resources/lang', 'rinvex.fort');
69
70
        // Load migrations
71
        $this->loadMigrationsFrom(__DIR__.'/../../database/migrations');
72
73
        // Subscribe the registered event listener
74
        $this->app['events']->subscribe('rinvex.fort.listener');
75
76
        // Add custom user provider
77
        $this->addCustomUserProvider();
78
79
        // Add custom session guard
80
        $this->addCustomSessionGuard();
81
82
        // Share current user instance with all views
83
        $this->app['view']->composer('*', function ($view) {
84
            $view->with('currentUser', Auth::user());
85
        });
86
    }
87
88
    /**
89
     * Bind the repositories into the IoC.
90
     *
91
     * @return void
92
     */
93
    protected function registerRepositories()
94
    {
95
        $this->bindAndAlias('rinvex.fort.role', RoleRepository::class);
96
        $this->bindAndAlias('rinvex.fort.user', UserRepository::class);
97
        $this->bindAndAlias('rinvex.fort.ability', AbilityRepository::class);
98
        $this->bindAndAlias('rinvex.fort.persistence', PersistenceRepository::class);
99
    }
100
101
    /**
102
     * Register the broker managers.
103
     *
104
     * @return void
105
     */
106
    protected function registerBrokerManagers()
107
    {
108
        // Register reset broker manager
109
        $this->app->singleton('rinvex.fort.resetter', function ($app) {
110
            return new BrokerManager($app, 'reset');
111
        });
112
113
        // Register verification broker manager
114
        $this->app->singleton('rinvex.fort.verifier', function ($app) {
115
            return new BrokerManager($app, 'verification');
116
        });
117
    }
118
119
    /**
120
     * Register the blade extensions.
121
     *
122
     * @return void
123
     */
124
    protected function registerBladeExtensions()
125
    {
126
        $this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) {
127
128
            // @role('writer')
129
            $bladeCompiler->directive('role', function ($model, $role) {
130
                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...
131
            });
132
            $bladeCompiler->directive('endrole', function () {
133
                return '<?php endif; ?>';
134
            });
135
136
            // @hasrole('writer')
137
            $bladeCompiler->directive('hasrole', function ($model, $role) {
138
                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...
139
            });
140
            $bladeCompiler->directive('endhasrole', function () {
141
                return '<?php endif; ?>';
142
            });
143
144
            // @hasanyrole(['writer', 'editor'])
145
            $bladeCompiler->directive('hasanyrole', function ($model, $roles) {
146
                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...
147
            });
148
            $bladeCompiler->directive('endhasanyrole', function () {
149
                return '<?php endif; ?>';
150
            });
151
152
            // @hasallroles(['writer', 'editor'])
153
            $bladeCompiler->directive('hasallroles', function ($model, $roles) {
154
                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...
155
            });
156
            $bladeCompiler->directive('endhasallroles', function () {
157
                return '<?php endif; ?>';
158
            });
159
        });
160
    }
161
162
    /**
163
     * Publish resources.
164
     *
165
     * @return void
166
     */
167
    protected function publishResources()
168
    {
169
        // Publish config
170
        $this->publishes([
171
            realpath(__DIR__.'/../../config/config.php') => config_path('rinvex.fort.php'),
172
        ], 'config');
173
174
        // Publish migrations
175
        $this->publishes([
176
            realpath(__DIR__.'/../../database/migrations') => database_path('migrations'),
177
        ], 'migrations');
178
179
        // Publish language phrases
180
        $this->publishes([
181
            realpath(__DIR__.'/../../resources/lang') => resource_path('lang/vendor/rinvex/fort'),
182
        ], 'lang');
183
184
        // Publish views
185
        $this->publishes([
186
            realpath(__DIR__.'/../../resources/views') => resource_path('views/vendor/rinvex/fort'),
187
        ], 'views');
188
    }
189
190
    /**
191
     * Load the routes.
192
     *
193
     * @param \Illuminate\Routing\Router $router
194
     *
195
     * @return void
196
     */
197
    public function loadRoutes(Router $router)
198
    {
199
        // Load routes
200
        if ($this->app->routesAreCached()) {
201
            $this->app->booted(function () {
202
                require $this->app->getCachedRoutesPath();
203
            });
204
        } else {
205
            // Load the application routes
206
            require __DIR__.'/../../routes/web.frontend.php';
207
208
            $this->app->booted(function () use ($router) {
209
                $router->getRoutes()->refreshNameLookups();
210
            });
211
        }
212
    }
213
214
    /**
215
     * Add custom user provider.
216
     *
217
     * @return void
218
     */
219
    protected function addCustomUserProvider()
220
    {
221
        $this->app['auth']->provider('rinvex.fort.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...
222
            // Return an instance of Rinvex\Fort\Contracts\UserRepositoryContract
223
            return $this->app['rinvex.fort.user'];
224
        });
225
    }
226
227
    /**
228
     * Add custom session guard.
229
     *
230
     * @return void
231
     */
232
    protected function addCustomSessionGuard()
233
    {
234
        // Add custom session guard
235
        $this->app['auth']->extend('rinvex.fort.session', function ($app, $name, array $config) {
236
            $provider = $app['auth']->createUserProvider($config['provider']);
237
238
            $guard = new SessionGuard($name, $provider, $app['session.store'], $app['request']);
239
240
            // When using the remember me functionality of the authentication services we
241
            // will need to be set the encryption instance of the guard, which allows
242
            // secure, encrypted cookie values to get generated for those cookies.
243
            if (method_exists($guard, 'setCookieJar')) {
244
                $guard->setCookieJar($this->app['cookie']);
245
            }
246
247
            if (method_exists($guard, 'setDispatcher')) {
248
                $guard->setDispatcher($this->app['events']);
249
            }
250
251
            if (method_exists($guard, 'setRequest')) {
252
                $guard->setRequest($this->app->refresh('request', $guard, 'setRequest'));
253
            }
254
255
            return $guard;
256
        });
257
    }
258
}
259