Passed
Push — master ( 4c4f3f...4700f4 )
by Sergei
02:48
created

addValidationClassToAttributes()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 17
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 7
c 1
b 0
f 0
nc 5
nop 3
dl 0
loc 17
ccs 8
cts 8
cp 1
crap 6
rs 9.2222
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 173
    protected function addValidationClassToAttributes(
39
        array &$attributes,
40
        FormModelInterface $formModel,
41
        string $attributeName,
42
    ): void {
43 173
        if (!$formModel->isValidated()) {
44 141
            return;
45
        }
46
47 32
        $hasErrors = $formModel->getFormErrors()->hasErrors($attributeName);
48
49 32
        if ($hasErrors && $this->invalidClass !== null) {
50 2
            Html::addCssClass($attributes, $this->invalidClass);
51
        }
52
53 32
        if (!$hasErrors && $this->validClass !== null) {
54 2
            Html::addCssClass($attributes, $this->validClass);
55
        }
56
    }
57
}
58