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

Validator   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 65%

Importance

Changes 0
Metric Value
dl 0
loc 50
ccs 13
cts 20
cp 0.65
rs 10
c 0
b 0
f 0
wmc 8
lcom 1
cbo 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A assert() 0 15 4
A validate() 0 11 3
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