Completed
Pull Request — master (#2)
by
unknown
03:49
created

AbstractValidator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 84
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 2
Metric Value
wmc 6
c 3
b 0
f 2
lcom 1
cbo 0
dl 0
loc 84
ccs 21
cts 21
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A isValid() 0 13 2
validate() 0 1 ?
A getErrors() 0 8 2
A getExpectedValidatorName() 0 10 1
1
<?php
2
3
namespace Iris\Validator;
4
5
use Iris\Transfer\Tracking\AbstractTracking;
6
7
abstract class AbstractValidator
8
{
9
    /**
10
     * @var array
11
     */
12
    protected $errors;
13
14
    /**
15
     * @var bool
16
     */
17
    protected $isValid;
18
19
    /**
20
     * @var bool
21
     */
22
    protected $isValidCalled;
23
24 35
    public function __construct()
25
    {
26 35
        $this->errors = [];
27 35
        $this->isValid = false;
28 35
        $this->isValidCalled = false;
29 35
    }
30
31
    /**
32
     * @param AbstractTracking $transfer
33
     * @throws \RuntimeException
34
     * @return bool
35
     */
36 30
    public function isValid(AbstractTracking $transfer)
37
    {
38 30
        $expectedTransferClass = $this->getExpectedValidatorName($this);
39
40 30
        if (!$transfer instanceof $expectedTransferClass) {
41 4
            throw new \RuntimeException(sprintf('Must be %s as parameter', $expectedTransferClass));
42
        }
43
44 26
        $this->isValid = $this->validate($transfer);
45 26
        $this->isValidCalled = true;
46
47 26
        return $this->isValid;
48
    }
49
50
    /**
51
     * The implementation must add the errors into the errors property. For example:
52
     *
53
     * $this->errors = [
54
     *    0 => 'error 1',
55
     *    1 => 'error 2',
56
     * ]
57
     *
58
     * @param $transfer
59
     * @return bool
60
     */
61
    protected abstract function validate($transfer);
0 ignored issues
show
Coding Style introduced by
The abstract declaration must precede the visibility declaration
Loading history...
62
63
    /**
64
     * @return array
65
     * @throws \RuntimeException
66
     */
67 30
    public function getErrors()
68
    {
69 30
        if (!$this->isValidCalled) {
70 4
            throw new \RuntimeException('You must call the isValid first');
71
        }
72
73 26
        return $this->errors;
74
    }
75
76
    /**
77
     * @param AbstractValidator $validator
78
     * @return string
79
     */
80 30
    protected function getExpectedValidatorName(AbstractValidator $validator)
81
    {
82 30
        $validatorClassName = get_class($validator);
83
84 30
        $path = explode('\\', $validatorClassName);
85
86 30
        $className = array_pop($path);
87
88 30
        return '\Iris\Transfer\Tracking\\' . $className;
89
    }
90
}
91