Authorized::passes()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 5
cts 6
cp 0.8333
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 3.0416
1
<?php
2
3
namespace Spatie\ValidationRules\Rules;
4
5
use Illuminate\Contracts\Validation\Rule;
6
use Illuminate\Support\Facades\Auth;
7
8
class Authorized implements Rule
9
{
10
    /** @var string */
11
    protected $ability;
12
13
    /** @var array */
14
    protected $arguments;
15
16
    /** @var string */
17
    protected $className;
18
19
    /** @var string */
20
    protected $attribute;
21
22 30
    /**@var string */
23
    protected $guard;
24 30
25
    public function __construct(string $ability, string $className, string $guard = null)
26 30
    {
27 30
        $this->ability = $ability;
28
        $this->className = $className;
29 30
        $this->guard = $guard;
30
    }
31 30
32
    public function passes($attribute, $value): bool
33 30
    {
34 24
        $this->attribute = $attribute;
35
36
        if (! $user = Auth::guard($this->guard)->user()) {
37 6
            return false;
38
        }
39
40
        if (! $model = app($this->className)->resolveRouteBinding($value)) {
41 6
            return false;
42
        }
43
44 6
        return $user->can($this->ability, $model);
45
    }
46 6
47
    public function message(): string
48 6
    {
49 6
        $classBasename = class_basename($this->className);
50 6
51 6
        return __('validationRules::messages.authorized', [
52
            'attribute' => $this->attribute,
53
            'ability' => $this->ability,
54
            'className' => $classBasename,
55
        ]);
56
    }
57
}
58