Completed
Pull Request — master (#402)
by Anton
04:50
created

AbstractRule::getTemplate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link https://github.com/bluzphp/framework
7
 */
8
9
declare(strict_types=1);
10
11
namespace Bluz\Validator\Rule;
12
13
use Bluz\Translator\Translator;
14
use Bluz\Validator\Exception\ValidatorException;
15
16
/**
17
 * Abstract validation rule
18
 *
19
 * @package  Bluz\Validator\Rule
20
 * @author   Anton Shevchuk
21
 */
22
abstract class AbstractRule
23
{
24
    /**
25
     * Template for error output
26
     *   - {{name}} - name of field
27
     *   - {{input}} - input value
28
     *
29
     * @var string
30
     */
31
    protected $template = '{{name}} has invalid value {{input}}';
32
33
    /**
34
     * Check input data
35
     *
36
     * @param  mixed $input
37
     * @return bool
38
     */
39
    abstract public function validate($input) : bool;
40
41
    /**
42
     * Invoke
43
     *
44
     * @param  mixed $input
45
     * @return bool
46
     */
47 1
    public function __invoke($input) : bool
48
    {
49 1
        return $this->validate($input);
50
    }
51
52
    /**
53
     * Assert
54
     *
55
     * @param  string $input
56
     * @return bool
57
     * @throws ValidatorException
58
     */
59 281
    public function assert($input)
60
    {
61 281
        if (!$this->validate($input)) {
62 150
            throw new ValidatorException();
63
        }
64 131
        return true;
65
    }
66
67
    /**
68
     * Set error template
69
     *
70
     * @param  string $template
71
     * @return void
72
     */
73
    public function setTemplate($template)
74
    {
75
        $this->template = $template;
76
    }
77
78
    /**
79
     * Get error template
80
     *
81
     * @return string
82
     */
83 3
    public function getTemplate()
84
    {
85 3
        return Translator::translate($this->template);
86
    }
87
88
    /**
89
     * Cast to string
90
     *
91
     * @return string
92
     */
93 68
    public function __toString()
94
    {
95 68
        return $this->getTemplate();
96
    }
97
}
98