Passed
Push — feature/back-to-summary-button... ( b22cf7...c47ef5 )
by Yonathan
09:27
created

ContainsObjectWithAttributeRule::arrayAny()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 8
rs 10
cc 3
nc 3
nop 2
1
<?php
2
3
namespace App\Services\Validation\Rules;
4
5
use Illuminate\Contracts\Validation\Rule;
6
use Illuminate\Support\Facades\Lang;
7
8
class ContainsObjectWithAttributeRule implements Rule
9
{
10
11
    protected $attributeName;
12
    protected $attributeValue;
13
14
    /**
15
     * Create a new rule instance.
16
     *
17
     * @param  string $attributeName
18
     * @param  mixed  $attributeValue
19
     * @return void
20
     */
21
    public function __construct($attributeName, $attributeValue)
22
    {
23
        $this->attributeName = $attributeName;
24
        $this->attributeValue = $attributeValue;
25
    }
26
27
    protected function arrayAny(array $array, callable $fn)
28
    {
29
        foreach ($array as $value) {
30
            if ($fn($value)) {
31
                return true;
32
            }
33
        }
34
        return false;
35
    }
36
37
    /**
38
     * This check passes if the $value is an array which contains an object
39
     *  with a attributeName relation equal to attributeValue
40
     * @param  mixed $attribute
41
     * @param  mixed $value
42
     * @return boolean
43
     */
44
    public function passes($attribute, $value)
45
    {
46
        return $this->arrayAny($value, function ($object) {
47
            return $object[$this->attributeName] == $this->attributeValue;
48
        });
49
    }
50
51
    public function message()
52
    {
53
        return Lang::get('validation.contains_object_with_attribute', ['relation' => $this->attributeName, 'attributeValue' => $this->attributeValue]);
54
    }
55
}
56