Completed
Pull Request — master (#962)
by Chris
02:21 queued 49s
created

PermissionServiceProvider   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 154
Duplicated Lines 33.77 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
dl 52
loc 154
rs 10
c 0
b 0
f 0
wmc 12
lcom 1
cbo 7

6 Methods

Rating   Name   Duplication   Size   Complexity  
A boot() 0 32 4
A register() 0 11 2
A registerModelBindings() 0 7 1
A registerBladeExtensions() 30 54 1
A registerMacroHelpers() 22 26 3
A getMigrationFileName() 0 10 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Spatie\Permission;
4
5
use Illuminate\Routing\Route;
6
use Illuminate\Support\Collection;
7
use Illuminate\Filesystem\Filesystem;
8
use Illuminate\Support\ServiceProvider;
9
use Illuminate\View\Compilers\BladeCompiler;
10
use Spatie\Permission\Contracts\Role as RoleContract;
11
use Spatie\Permission\Contracts\Permission as PermissionContract;
12
13
class PermissionServiceProvider extends ServiceProvider
14
{
15
    public function boot(PermissionRegistrar $permissionLoader, Filesystem $filesystem)
16
    {
17
        if (isNotLumen()) {
18
            $this->publishes([
19
                __DIR__.'/../config/permission.php' => config_path('permission.php'),
20
            ], 'config');
21
22
            $this->publishes([
23
                __DIR__.'/../database/migrations/create_permission_tables.php.stub' => $this->getMigrationFileName($filesystem),
24
            ], 'migrations');
25
26
            if (app()->version() >= '5.5') {
27
                $this->registerMacroHelpers();
28
            }
29
        }
30
31
        if ($this->app->runningInConsole()) {
32
            $this->commands([
33
                Commands\CacheReset::class,
34
                Commands\CreateRole::class,
35
                Commands\CreatePermission::class,
36
            ]);
37
        }
38
39
        $this->registerModelBindings();
40
41
        $permissionLoader->registerPermissions();
42
43
        $this->app->singleton(PermissionRegistrar::class, function ($app) use ($permissionLoader) {
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...
44
            return $permissionLoader;
45
        });
46
    }
47
48
    public function register()
49
    {
50
        if (isNotLumen()) {
51
            $this->mergeConfigFrom(
52
                __DIR__.'/../config/permission.php',
53
                'permission'
54
            );
55
        }
56
57
        $this->registerBladeExtensions();
58
    }
59
60
    protected function registerModelBindings()
61
    {
62
        $config = $this->app->config['permission.models'];
0 ignored issues
show
Bug introduced by
Accessing config on the interface Illuminate\Contracts\Foundation\Application suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
63
64
        $this->app->bind(PermissionContract::class, $config['permission']);
65
        $this->app->bind(RoleContract::class, $config['role']);
66
    }
67
68
    protected function registerBladeExtensions()
69
    {
70
        $this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) {
71 View Code Duplication
            $bladeCompiler->directive('role', function ($arguments) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
72
                list($role, $guard) = explode(',', $arguments.',');
73
74
                return "<?php if(auth({$guard})->check() && auth({$guard})->user()->hasRole({$role})): ?>";
75
            });
76 View Code Duplication
            $bladeCompiler->directive('elserole', function ($arguments) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
77
                list($role, $guard) = explode(',', $arguments.',');
78
79
                return "<?php elseif(auth({$guard})->check() && auth({$guard})->user()->hasRole({$role})): ?>";
80
            });
81
            $bladeCompiler->directive('endrole', function () {
82
                return '<?php endif; ?>';
83
            });
84
85 View Code Duplication
            $bladeCompiler->directive('hasrole', function ($arguments) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
86
                list($role, $guard) = explode(',', $arguments.',');
87
88
                return "<?php if(auth({$guard})->check() && auth({$guard})->user()->hasRole({$role})): ?>";
89
            });
90
            $bladeCompiler->directive('endhasrole', function () {
91
                return '<?php endif; ?>';
92
            });
93
94 View Code Duplication
            $bladeCompiler->directive('hasanyrole', function ($arguments) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
95
                list($roles, $guard) = explode(',', $arguments.',');
96
97
                return "<?php if(auth({$guard})->check() && auth({$guard})->user()->hasAnyRole({$roles})): ?>";
98
            });
99
            $bladeCompiler->directive('endhasanyrole', function () {
100
                return '<?php endif; ?>';
101
            });
102
103 View Code Duplication
            $bladeCompiler->directive('hasallroles', function ($arguments) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
104
                list($roles, $guard) = explode(',', $arguments.',');
105
106
                return "<?php if(auth({$guard})->check() && auth({$guard})->user()->hasAllRoles({$roles})): ?>";
107
            });
108
            $bladeCompiler->directive('endhasallroles', function () {
109
                return '<?php endif; ?>';
110
            });
111
112 View Code Duplication
            $bladeCompiler->directive('unlessrole', function ($arguments) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
113
                list($role, $guard) = explode(',', $arguments.',');
114
115
                return "<?php if(!auth({$guard})->check() || ! auth({$guard})->user()->hasRole({$role})): ?>";
116
            });
117
            $bladeCompiler->directive('endunlessrole', function () {
118
                return '<?php endif; ?>';
119
            });
120
        });
121
    }
122
123
    protected function registerMacroHelpers()
124
    {
125 View Code Duplication
        Route::macro('role', function ($roles = []) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
126
            if (! is_array($roles)) {
127
                $roles = [$roles];
128
            }
129
130
            $roles = implode('|', $roles);
131
132
            $this->middleware("role:$roles");
0 ignored issues
show
Bug introduced by
The method middleware() does not seem to exist on object<Spatie\Permission...missionServiceProvider>.

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...
133
134
            return $this;
135
        });
136
137 View Code Duplication
        Route::macro('permission', function ($permissions = []) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
138
            if (! is_array($permissions)) {
139
                $permissions = [$permissions];
140
            }
141
142
            $permissions = implode('|', $permissions);
143
144
            $this->middleware("permission:$permissions");
0 ignored issues
show
Bug introduced by
The method middleware() does not seem to exist on object<Spatie\Permission...missionServiceProvider>.

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...
145
146
            return $this;
147
        });
148
    }
149
150
    /**
151
     * Returns existing migration file if found, else uses the current timestamp
152
     *
153
     * @param Filesystem $filesystem
154
     * @return string
155
     */
156
    protected function getMigrationFileName(Filesystem $filesystem): string
157
    {
158
        $timestamp = date('Y_m_d_His');
159
160
        return Collection::make($this->app->databasePath().DIRECTORY_SEPARATOR.'migrations'.DIRECTORY_SEPARATOR)
0 ignored issues
show
Bug introduced by
The method databasePath does only exist in Illuminate\Foundation\Application, but not in Illuminate\Contracts\Foundation\Application.

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...
161
            ->flatMap(function ($path) use ($filesystem) {
162
                return $filesystem->glob($path.'*_create_permission_tables.php');
163
            })->push($this->app->databasePath()."/migrations/{$timestamp}_create_permission_tables.php")
0 ignored issues
show
Bug introduced by
The method databasePath does only exist in Illuminate\Foundation\Application, but not in Illuminate\Contracts\Foundation\Application.

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...
164
            ->first();
165
    }
166
}
167