Completed
Push — master ( 0d5c20...3309bb )
by Changwan
09:19
created

Validator::assert()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.1755

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 4
nop 1
dl 0
loc 15
ccs 7
cts 9
cp 0.7778
crap 4.1755
rs 9.2
c 0
b 0
f 0
1
<?php
2
namespace Wandu\Validator;
3
4
use Wandu\Validator\Exception\InvalidValueException;
5
6
class Validator
7
{
8
    /** @var \Wandu\Validator\TesterFactory */
9
    protected $tester;
10
    
11
    /** @var string|\Wandu\Validator\Contracts\Rule */
12
    protected $rule;
13
    
14
    public function __construct(TesterFactory $tester, $rule)
15 4
    {
16
        $this->tester = $tester;
17 4
        $this->rule = $rule;
18 4
    }
19
20
    /**
21
     * @param mixed $data
22
     * @return void
23
     */
24 4
    public function assert($data)
25
    {
26 4
        if (is_string($this->rule)) {
27 1
            if (!$this->tester->parse($this->rule)->test($data)) {
28 1
                throw new InvalidValueException([$this->rule]);
29
            }
30
            return;
31 3
        }
32
33
        $errorBag = new ErrorBag();
34
        $this->rule->define(new AssertRuleDefinition($this->tester, $errorBag, $data, $data));
35
        if (count($errorBag)) {
36
            throw new InvalidValueException($errorBag->errors());
37 3
        }
38 3
    }
39 3
40 2
    /**
41
     * @param mixed $data
42 3
     * @return bool
43
     */
44
    public function validate($data): bool
45
    {
46
        if (is_string($this->rule)) {
47
            return $this->tester->parse($this->rule)->test($data);
48
        }
49
        try {
50
            $this->assert($data);
51
            return true;
52
        } catch (InvalidValueException $e) {}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
53
        return false;
54
    }
55
}
56