Completed
Push — develop ( 10b573...34b970 )
by Abdelrahman
09:38
created

FortServiceProvider::boot()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 47
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 3
eloc 26
nc 4
nop 1
dl 0
loc 47
rs 9.0303
c 4
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cortex\Fort\Providers;
6
7
use Illuminate\Http\Request;
8
use Rinvex\Fort\Models\Role;
9
use Rinvex\Fort\Models\User;
10
use Illuminate\Routing\Router;
11
use Rinvex\Fort\Models\Ability;
12
use Rinvex\Fort\Models\Session;
13
use Illuminate\Support\ServiceProvider;
14
use Cortex\Fort\Handlers\GenericHandler;
15
use Cortex\Fort\Http\Middleware\Abilities;
16
use Cortex\Fort\Http\Middleware\NoHttpCache;
17
use Cortex\Fort\Http\Middleware\Authenticate;
18
use Cortex\Fort\Console\Commands\SeedCommand;
19
use Cortex\Fort\Console\Commands\InstallCommand;
20
use Cortex\Fort\Console\Commands\MigrateCommand;
21
use Cortex\Fort\Console\Commands\PublishCommand;
22
use Cortex\Fort\Console\Commands\RollbackCommand;
23
use Cortex\Fort\Http\Middleware\UpdateLastActivity;
24
use Illuminate\Database\Eloquent\Relations\Relation;
25
use Cortex\Fort\Http\Middleware\RedirectIfAuthenticated;
26
27
class FortServiceProvider extends ServiceProvider
28
{
29
    /**
30
     * The commands to be registered.
31
     *
32
     * @var array
33
     */
34
    protected $commands = [
35
        SeedCommand::class => 'command.cortex.fort.seed',
36
        InstallCommand::class => 'command.cortex.fort.install',
37
        MigrateCommand::class => 'command.cortex.fort.migrate',
38
        PublishCommand::class => 'command.cortex.fort.publish',
39
        RollbackCommand::class => 'command.cortex.fort.rollback',
40
    ];
41
42
    /**
43
     * Register any application services.
44
     *
45
     * This service provider is a great spot to register your various container
46
     * bindings with the application. As you can see, we are registering our
47
     * "Registrar" implementation here. You can add your own bindings too!
48
     *
49
     * @return void
50
     */
51
    public function register(): void
52
    {
53
        $this->mergeConfigFrom(realpath(__DIR__.'/../../config/config.php'), 'cortex.fort');
54
55
        // Register console commands
56
        ! $this->app->runningInConsole() || $this->registerCommands();
57
    }
58
59
    /**
60
     * Bootstrap any application services.
61
     *
62
     * @return void
63
     */
64
    public function boot(Router $router): void
65
    {
66
        // Attach request macro
67
        $this->attachRequestMacro();
68
69
        // Bind route models and constrains
70
        $router->pattern('ability', '[0-9]+');
71
        $router->pattern('role', '[a-z0-9-]+');
72
        $router->pattern('user', '[a-zA-Z0-9_-]+');
73
        $router->pattern('session', '[a-zA-Z0-9]+');
74
        $router->model('ability', Ability::class);
75
        $router->model('session', Session::class);
76
        $router->model('role', Role::class);
77
        $router->model('user', User::class);
78
79
        // Map relations
80
        Relation::morphMap([
81
            'role' => config('rinvex.fort.models.role'),
82
            'ability' => config('rinvex.fort.models.ability'),
83
            'user' => config('auth.providers.'.config('auth.guards.'.config('auth.defaults.guard').'.provider').'.model'),
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 122 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
86
        // Load resources
87
        require __DIR__.'/../../routes/breadcrumbs.php';
88
        $this->loadRoutesFrom(__DIR__.'/../../routes/web.php');
89
        $this->loadViewsFrom(__DIR__.'/../../resources/views', 'cortex/fort');
90
        $this->loadTranslationsFrom(__DIR__.'/../../resources/lang', 'cortex/fort');
91
        ! $this->app->runningInConsole() || $this->loadMigrationsFrom(__DIR__.'/../../database/migrations');
92
        $this->app->afterResolving('blade.compiler', function () {
93
            require __DIR__.'/../../routes/menus.php';
94
        });
95
96
        // Publish Resources
97
        ! $this->app->runningInConsole() || $this->publishResources();
98
99
        // Register event handlers
100
        $this->app['events']->subscribe(GenericHandler::class);
101
102
        // Register attributes entities
103
        app('rinvex.attributes.entities')->push('user');
104
105
        // Override middlware
106
        $this->overrideMiddleware($router);
107
108
        // Register menus
109
        $this->registerMenus();
110
    }
111
112
    /**
113
     * Publish resources.
114
     *
115
     * @return void
116
     */
117
    protected function publishResources(): void
118
    {
119
        $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...
120
        $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...
121
        $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...
122
        $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...
123
    }
124
125
    /**
126
     * Register console commands.
127
     *
128
     * @return void
129
     */
130
    protected function registerCommands(): void
131
    {
132
        // Register artisan commands
133
        foreach ($this->commands as $key => $value) {
134
            $this->app->singleton($value, $key);
135
        }
136
137
        $this->commands(array_values($this->commands));
138
    }
139
140
    /**
141
     * Register console commands.
142
     *
143
     * @return void
144
     */
145
    protected function attachRequestMacro(): void
146
    {
147
        Request::macro('attemptUser', function (string $guard = null) {
148
            $twofactor = $this->session()->get('rinvex.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...
149
150
            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...
151
        });
152
    }
153
154
    /**
155
     * Register menus.
156
     *
157
     * @return void
158
     */
159
    protected function registerMenus(): void
160
    {
161
        $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...
162
    }
163
    /**
164
     * Override middleware.
165
     *
166
     * @param \Illuminate\Routing\Router $router
167
     *
168
     * @return void
169
     */
170
    protected function overrideMiddleware(Router $router): void
171
    {
172
        // Append middleware to the 'web' middlware group
173
        $router->pushMiddlewareToGroup('web', Abilities::class);
174
        $router->pushMiddlewareToGroup('web', UpdateLastActivity::class);
175
176
        // Override route middleware on the fly
177
        $router->aliasMiddleware('auth', Authenticate::class);
178
        $router->aliasMiddleware('nohttpcache', NoHttpCache::class);
179
        $router->aliasMiddleware('guest', RedirectIfAuthenticated::class);
180
    }
181
}
182