Passed
Push — develop ( 4e7190...14b77f )
by Richard
13:58
created

ConditionallyRequired::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Riclep\StoryblokForms\Rules;
4
5
use Illuminate\Contracts\Validation\DataAwareRule;
6
use Illuminate\Contracts\Validation\InvokableRule;
7
8
class ConditionallyRequired implements DataAwareRule, InvokableRule
9
{
10
11
	protected $conditional;
12
13
	public function __construct($conditional) {
14
		$this->conditional = $conditional;
15
	}
16
17
    /**
18
     * Run the validation rule.
19
     *
20
     * @param  string  $attribute
21
     * @param  mixed  $value
22
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
23
     * @return void
24
     */
25
    public function __invoke($attribute, $value, $fail)
26
    {
27
	    $causationFieldValue = data_get($this->data, $this->conditional['field']);
28
29
		$condition = $this->conditional['condition'];
30
		$operator = $this->conditional['operator'];
31
32
		$fieldIsRequired = false;
33
34
	    if ($operator === '>') {
35
		    $fieldIsRequired = $causationFieldValue > $condition;
36
	    } else if ($operator === '<') {
37
		    $fieldIsRequired = $causationFieldValue < $condition;
38
	    } else if ($operator === '==') {
39
		    $fieldIsRequired = $causationFieldValue == $condition;
40
	    }  else if ($operator === '===') {
41
		    $fieldIsRequired = $causationFieldValue === $condition;
42
	    } else if ($operator === '!=') {
43
		    $fieldIsRequired = $causationFieldValue != $condition;
44
	    }  else if ($operator === '!==') {
45
		    $fieldIsRequired = $causationFieldValue !== $condition;
46
	    } else if ($operator === '>=') {
47
		    $fieldIsRequired = $causationFieldValue >= $condition;
48
	    } else if ($operator === '<=') {
49
		    $fieldIsRequired = $causationFieldValue <= $condition;
50
	    }
51
52
	    if ($fieldIsRequired && !$value) {
53
		    $fail('This field is required.');
54
	    }
55
    }
56
57
	/**
58
	 * Outputs the HTML version of the validation
59
	 *
60
	 * @return string
61
	 */
62
	public function __toString()
63
	{
64
		return '';
65
	}
66
67
	/**
68
	 * Set the data under validation.
69
	 *
70
	 * @param array $data
71
	 * @return $this
72
	 */
73
	public function setData($data)
74
	{
75
		$this->data = $data;
0 ignored issues
show
Bug Best Practice introduced by
The property data does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
76
77
		return $this;
78
	}
79
}
80