Passed
Pull Request — master (#192)
by Alexander
03:02
created

ValidationClassTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 16
c 0
b 0
f 0
dl 0
loc 42
ccs 16
cts 16
cp 1
rs 10
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A invalidClass() 0 5 1
A addValidationClassToTagAttributes() 0 17 6
A validClass() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Form\Field\Base\ValidationClass;
6
7
use Yiisoft\Form\FormModelInterface;
8
use Yiisoft\Html\Html;
9
10
/**
11
 * @psalm-require-extends \Yiisoft\Form\Field\Base\BaseField
12
 */
13
trait ValidationClassTrait
14
{
15
    private ?string $invalidClass = null;
16
    private ?string $validClass = null;
17
18
    /**
19
     * Set invalid CSS class.
20
     */
21 4
    public function invalidClass(string $class): self
22
    {
23 4
        $new = clone $this;
24 4
        $new->invalidClass = $class;
25 4
        return $new;
26
    }
27
28
    /**
29
     * Set valid CSS class.
30
     */
31 4
    public function validClass(string $class): self
32
    {
33 4
        $new = clone $this;
34 4
        $new->validClass = $class;
35 4
        return $new;
36
    }
37
38 142
    protected function addValidationClassToTagAttributes(
39
        array &$tagAttributes,
40
        FormModelInterface $formModel,
41
        string $attributeName,
42
    ): void {
43 142
        if (!$formModel->isValidated()) {
44 114
            return;
45
        }
46
47 28
        $hasErrors = $formModel->getFormErrors()->hasErrors($attributeName);
48
49 28
        if ($hasErrors && $this->invalidClass !== null) {
50 2
            Html::addCssClass($tagAttributes, $this->invalidClass);
51
        }
52
53 28
        if (!$hasErrors && $this->validClass !== null) {
54 2
            Html::addCssClass($tagAttributes, $this->validClass);
55
        }
56
    }
57
}
58