Completed
Pull Request — master (#122)
by Issei
02:32
created

MultipleValidationWithAnd::isValid()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 18
ccs 13
cts 13
cp 1
rs 8.8571
cc 5
eloc 12
nc 5
nop 2
crap 5
1
<?php
2
3
namespace Egulias\EmailValidator\Validation;
4
5
use Egulias\EmailValidator\EmailLexer;
6
use Egulias\EmailValidator\Exception\InvalidEmail;
7
use Egulias\EmailValidator\Validation\Exception\EmptyValidationList;
8
9
class MultipleValidationWithAnd implements EmailValidation
10
{
11
    /**
12
     * @var EmailValidation[]
13
     */
14
    private $validations = [];
15
16
    /**
17
     * @var array
18
     */
19
    private $warnings = [];
20
21
    /**
22
     * @var InvalidEmail
23
     */
24
    private $error;
25
26
    /**
27
     * @var bool
28
     */
29
    private $breakIfError;
30
31
    /**
32
     * @param EmailValidation[] $validations  The validations.
33
     * @param bool              $breakIfError If true, it breaks out of validation loop when error occurs,
34
     *                                        it means returned MultipleErrors might not contain all causes of errors. (false by default)
35
     */
36 6
    public function __construct(array $validations, $breakIfError = false)
37
    {
38 6
        if (count($validations) == 0) {
39 1
            throw new EmptyValidationList();
40
        }
41
        
42 5
        $this->validations = $validations;
43 5
        $this->breakIfError = $breakIfError;
44 5
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49 5
    public function isValid($email, EmailLexer $emailLexer)
50
    {
51 5
        $result = true;
52 5
        $errors = [];
53 5
        foreach ($this->validations as $validation) {
54 5
            $emailLexer->reset();
55 5
            $result = $result && $validation->isValid($email, $emailLexer);
56 5
            $this->warnings = array_merge($this->warnings, $validation->getWarnings());
57 5
            $errors[] = $validation->getError();
58
59 5
            if (!$result && $this->breakIfError) {
60 1
                break;
61
            }
62 5
        }
63 5
        $this->error = new MultipleErrors($errors);
64
        
65 5
        return $result;
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71 3
    public function getError()
72
    {
73 3
        return $this->error;
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     */
79 2
    public function getWarnings()
80
    {
81 2
        return $this->warnings;
82
    }
83
}
84