Validator::fails()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 11
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Laravel\ExtraFieldsValidator;
6
7
use Illuminate\Validation\Validator as BaseValidator;
8
9
class Validator extends BaseValidator
10
{
11
    private array $extraCallbacks = [];
12
13
    public function afterSuccess(callable $callback): Validator
14
    {
15
        return $this->registerExtraCallback('success', $callback);
16
    }
17
18
    public function afterFailure(callable $callback): Validator
19
    {
20
        return $this->registerExtraCallback('fail', $callback);
21
    }
22
23
    public function fails()
24
    {
25
        $fails = !$this->passes();
26
27
        if ($fails) {
28
            $this->runExtraCallbacks('fail');
29
        } else {
30
            $fails = $this->runExtraCallbacks('success') === false;
31
        }
32
33
        return $fails;
34
    }
35
36
    private function registerExtraCallback(string $type, callable $callback): Validator
37
    {
38
        if (!isset($this->extraCallbacks[$type]) || !is_array($this->extraCallbacks[$type])) {
39
            $this->extraCallbacks[$type] = [];
40
        }
41
42
        $this->extraCallbacks[$type][] = fn () => call_user_func_array($callback, [$this]);
43
44
        return $this;
45
    }
46
47
    private function runExtraCallbacks(string $type): bool
48
    {
49
        if (empty($this->extraCallbacks[$type])) {
50
            return true;
51
        }
52
53
        foreach ($this->extraCallbacks[$type] as $callback) {
54
            if ($callback() === false) {
55
                return false;
56
            }
57
        }
58
59
        $this->extraCallbacks[$type] = [];
60
61
        return true;
62
    }
63
}
64