Completed
Push — master ( bd2863...897b5a )
by Shcherbak
45:04 queued 30:10
created

CallBackValidatorTest   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
c 1
b 0
f 0
lcom 1
cbo 4
dl 0
loc 74
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B testLen() 0 33 2
B testEmailVirtualDbValidation() 0 36 3
1
<?php
2
3
  namespace Tests\Fiv\Form\Validator;
4
5
  use Fiv\Form\Form;
6
  use Fiv\Form\Validator\CallBackValidator;
7
8
  /**
9
   *
10
   */
11
  class CallBackValidatorTest extends \PHPUnit_Framework_TestCase {
12
13
    public function testLen() {
14
      $lengthValidator = new CallBackValidator(function ($value) {
15
        return strlen($value) > 3 and strlen($value) < 10;
16
      });
17
18
      $form = new Form();
19
      $form->input('login')
20
        ->addValidator($lengthValidator);
21
22
      $form->setData([
23
        $form->getUid() => 1,
24
        'login' => 'testLogin',
25
      ]);
26
27
      $this->assertTrue($form->isValid());
28
      $this->assertFalse($lengthValidator->hasErrors());
29
30
31
      $form->setData([
32
        $form->getUid() => 1,
33
        'login' => 'tes',
34
      ]);
35
36
      $this->assertFalse($form->isValid());
37
      $this->assertTrue($lengthValidator->hasErrors());
38
39
      $form->setData([
40
        $form->getUid() => 1,
41
        'login' => 'testtesttesttesttesttesttesttest',
42
      ]);
43
44
      $this->assertFalse($form->isValid());
45
    }
46
47
48
    public function testEmailVirtualDbValidation() {
49
      $form = new Form();
50
51
      $existEmailList = [
52
        '[email protected]',
53
        '[email protected]',
54
      ];
55
56
      $callBackValidator = (new CallBackValidator(function ($value) use ($existEmailList) {
57
        if (empty($value)) {
58
          return true;
59
        }
60
        if (in_array($value, $existEmailList)) {
61
          return false;
62
        }
63
        return true;
64
      }))->setErrorMessage('Email already exist!');
65
66
      $input = $form->input('email');
67
      $input->addValidator($callBackValidator);
68
69
      $form->setData([
70
        $form->getUid() => 1,
71
        'email' => '[email protected]',
72
      ]);
73
74
      $this->assertFalse($form->isValid());
75
      $this->assertEquals('Email already exist!', $callBackValidator->getFirstError());
76
77
      $form->setData([
78
        $form->getUid() => 1,
79
        'email' => '[email protected]',
80
      ]);
81
82
      $this->assertTrue($form->isValid());
83
    }
84
  }
85