-
Notifications
You must be signed in to change notification settings - Fork 68
/
ConditionalRules.php
83 lines (74 loc) · 2.43 KB
/
ConditionalRules.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
<?php
namespace Illuminate\Validation;
use Illuminate\Support\Fluent;
class ConditionalRules
{
/**
* The boolean condition indicating if the rules should be added to the attribute.
*
* @var callable|bool
*/
protected $condition;
/**
* The rules to be added to the attribute.
*
* @var \Illuminate\Contracts\Validation\ValidationRule|\Illuminate\Contracts\Validation\InvokableRule|\Illuminate\Contracts\Validation\Rule|\Closure|array|string
*/
protected $rules;
/**
* The rules to be added to the attribute if the condition fails.
*
* @var \Illuminate\Contracts\Validation\ValidationRule|\Illuminate\Contracts\Validation\InvokableRule|\Illuminate\Contracts\Validation\Rule|\Closure|array|string
*/
protected $defaultRules;
/**
* Create a new conditional rules instance.
*
* @param callable|bool $condition
* @param \Illuminate\Contracts\Validation\ValidationRule|\Illuminate\Contracts\Validation\InvokableRule|\Illuminate\Contracts\Validation\Rule|\Closure|array|string $rules
* @param \Illuminate\Contracts\Validation\ValidationRule|\Illuminate\Contracts\Validation\InvokableRule|\Illuminate\Contracts\Validation\Rule|\Closure|array|string $defaultRules
* @return void
*/
public function __construct($condition, $rules, $defaultRules = [])
{
$this->condition = $condition;
$this->rules = $rules;
$this->defaultRules = $defaultRules;
}
/**
* Determine if the conditional rules should be added.
*
* @param array $data
* @return bool
*/
public function passes(array $data = [])
{
return is_callable($this->condition)
? call_user_func($this->condition, new Fluent($data))
: $this->condition;
}
/**
* Get the rules.
*
* @param array $data
* @return array
*/
public function rules(array $data = [])
{
return is_string($this->rules)
? explode('|', $this->rules)
: value($this->rules, new Fluent($data));
}
/**
* Get the default rules.
*
* @param array $data
* @return array
*/
public function defaultRules(array $data = [])
{
return is_string($this->defaultRules)
? explode('|', $this->defaultRules)
: value($this->defaultRules, new Fluent($data));
}
}