-
Notifications
You must be signed in to change notification settings - Fork 10.7k
/
Can.php
86 lines (73 loc) · 1.8 KB
/
Can.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
namespace Illuminate\Validation\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Contracts\Validation\ValidatorAwareRule;
use Illuminate\Support\Facades\Gate;
class Can implements Rule, ValidatorAwareRule
{
/**
* The ability to check.
*
* @var string
*/
protected $ability;
/**
* The arguments to pass to the authorization check.
*
* @var array
*/
protected $arguments;
/**
* The current validator instance.
*
* @var \Illuminate\Validation\Validator
*/
protected $validator;
/**
* Constructor.
*
* @param string $ability
* @param array $arguments
*/
public function __construct($ability, array $arguments = [])
{
$this->ability = $ability;
$this->arguments = $arguments;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$arguments = $this->arguments;
$model = array_shift($arguments);
return Gate::allows($this->ability, array_filter([$model, ...$arguments, $value]));
}
/**
* Get the validation error message.
*
* @return array
*/
public function message()
{
$message = $this->validator->getTranslator()->get('validation.can');
return $message === 'validation.can'
? ['The :attribute field contains an unauthorized value.']
: $message;
}
/**
* Set the current validator.
*
* @param \Illuminate\Validation\Validator $validator
* @return $this
*/
public function setValidator($validator)
{
$this->validator = $validator;
return $this;
}
}