Passed
Pull Request — master (#54)
by Alexander
12:02
created

RulesTest::testCallback()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 9
c 2
b 0
f 0
nc 1
nop 0
dl 0
loc 17
rs 9.9666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Tests;
6
7
use Yiisoft\Validator\Rules;
8
use PHPUnit\Framework\TestCase;
9
use Yiisoft\Validator\Result;
10
use Yiisoft\Validator\Rule\Number;
11
use Yiisoft\Validator\Rule\Required;
12
13
class RulesTest extends TestCase
14
{
15
    public function testMethodSyntax(): void
16
    {
17
        $rules = new Rules();
18
        $rules->add(new Required());
19
        $rules->add((new Number())->max(10));
20
21
        $result = $rules->validate(42);
22
        $this->assertFalse($result->isValid());
23
        $this->assertCount(1, $result->getErrors());
24
    }
25
26
    public function testArraySyntax(): void
27
    {
28
        $rules = new Rules(
29
            [
30
                new Required(),
31
                (new Number())->max(10)
32
            ]
33
        );
34
35
        $result = $rules->validate(42);
36
        $this->assertFalse($result->isValid());
37
        $this->assertCount(1, $result->getErrors());
38
    }
39
40
    public function testCallback(): void
41
    {
42
        $rules = new Rules(
43
            [
44
                static function ($value): Result {
45
                    $result = new Result();
46
                    if ($value !== 42) {
47
                        $result->addError('Value should be 42!');
48
                    }
49
                    return $result;
50
                }
51
            ]
52
        );
53
54
        $result = $rules->validate(41);
55
        $this->assertFalse($result->isValid());
56
        $this->assertCount(1, $result->getErrors());
57
    }
58
59
    public function testSkipOnError()
60
    {
61
        $rules = new Rules(
62
            [
63
                (new Number())->min(10),
64
                (new Number())->min(10)->skipOnError(false),
65
                (new Number())->min(10)
66
            ]
67
        );
68
69
        $result = $rules->validate(1);
70
71
        $this->assertFalse($result->isValid());
72
        $this->assertCount(2, $result->getErrors());
73
    }
74
}
75