ApplyMap::message()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Monooso\Apposite\Rules;
4
5
use Illuminate\Contracts\Validation\Rule;
6
use Illuminate\Contracts\Validation\Validator as ValidatorContract;
7
use Illuminate\Support\Facades\Validator;
8
9
class ApplyMap implements Rule
10
{
11
    /** @var array */
12
    protected $messages;
13
14
    /** @var array|string */
15
    protected $rules;
16
17
    /**
18
     * Initialise the custom rule
19
     *
20
     * @param string $key
21
     * @param array  $map
22
     */
23 9
    public function __construct(string $key, array $map)
24
    {
25 9
        $this->rules = (array_key_exists($key, $map)) ? $map[$key] : [];
26 9
        $this->messages = [];
27 9
    }
28
29
    /**
30
     * Determine if the validation rule passes
31
     *
32
     * @param string $attribute
33
     * @param mixed  $value
34
     *
35
     * @return bool
36
     */
37 9
    public function passes($attribute, $value)
38
    {
39 9
        $validator = $this->makeValidator($attribute, $value);
40
41 9
        $this->messages = $validator->fails() ? $validator->errors()->all() : [];
42
43 9
        return count($this->messages) === 0;
44
    }
45
46
    /**
47
     * Build the validator instance, to validate the given attribute and value
48
     *
49
     * @param string $attribute
50
     * @param mixed  $value
51
     *
52
     * @return ValidatorContract
53
     */
54 9
    protected function makeValidator(string $attribute, $value): ValidatorContract
55
    {
56 9
        return Validator::make([$attribute => $value], [$attribute => $this->rules]);
57
    }
58
59
    /**
60
     * Get the validation error message.
61
     *
62
     * @return string|array
63
     */
64 6
    public function message()
65
    {
66 6
        return $this->messages;
67
    }
68
}
69