Passed
Push — master ( 893d1e...31005e )
by Kirill
03:35
created

AbstractChecker::getMessage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 10
rs 10
cc 2
nc 2
nop 4
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Validation;
13
14
use Spiral\Translator\Traits\TranslatorTrait;
15
16
/**
17
 * @inherit-messages
18
 */
19
abstract class AbstractChecker implements CheckerInterface
20
{
21
    use TranslatorTrait;
22
23
    /** Error messages associated with checker method by name. */
24
    public const MESSAGES = [];
25
26
    /** Default error message if no other messages are found. */
27
    public const DEFAULT_MESSAGE = '[[The condition `{method}` was not met.]]';
28
29
    /** List of methods which are allowed to handle empty values. */
30
    public const ALLOW_EMPTY_VALUES = [];
31
32
    /** @var ValidatorInterface */
33
    private $validator;
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public function ignoreEmpty(string $method, $value, array $args): bool
39
    {
40
        if (!empty($value)) {
41
            return false;
42
        }
43
44
        return !in_array($method, static::ALLOW_EMPTY_VALUES, true);
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50
    public function check(
51
        ValidatorInterface $v,
52
        string $method,
53
        string $field,
54
        $value,
55
        array $args = []
56
    ): bool {
57
        try {
58
            $this->validator = $v;
59
            array_unshift($args, $value);
60
61
            return call_user_func_array([$this, $method], $args);
62
        } finally {
63
            $this->validator = null;
64
        }
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70
    public function getMessage(string $method, string $field, $value, array $arguments = []): string
71
    {
72
        $messages = static::MESSAGES;
73
        if (isset($messages[$method])) {
74
            array_unshift($arguments, $field);
75
76
            return $this->say(static::MESSAGES[$method], $arguments);
77
        }
78
79
        return $this->say(static::DEFAULT_MESSAGE, compact('method'));
80
    }
81
82
    /**
83
     * @return ValidatorInterface
84
     */
85
    protected function getValidator(): ValidatorInterface
86
    {
87
        return $this->validator;
88
    }
89
}
90