Passed
Push — master ( 2933e0...94de28 )
by Bruno
12:05 queued 08:32
created

Renderable::editable()   B

Complexity

Conditions 8
Paths 7

Size

Total Lines 31
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 22
c 1
b 1
f 0
dl 0
loc 31
rs 8.4444
cc 8
nc 7
nop 3
1
<?php declare(strict_types=1);
2
3
namespace Formularium\Frontend\HTMLValidation;
4
5
use Formularium\Field;
6
use Formularium\HTMLNode;
7
use Formularium\Validator\MaxLength;
8
use Formularium\Validator\MinLength;
9
use Formularium\Validator\Regex;
10
11
class Renderable extends \Formularium\Renderable
12
{
13
    public function viewable($value, Field $field, HTMLNode $previous): HTMLNode
14
    {
15
        return $previous;
16
    }
17
18
    public function editable($value, Field $field, HTMLNode $previous): HTMLNode
19
    {
20
        $validators = $field->getValidators();
21
22
        $element = $this->getInput($previous);
23
        if (!$element) {
24
            return $previous;
25
        }
26
27
        foreach ($validators as $validator => $data) {
28
            switch ($validator) {
29
            case MinLength::class:
30
                $element->setAttribute('minlength', $field->getValidatorOption($validator, 'value', ''));
31
                break;
32
            case MaxLength::class:
33
                $element->setAttribute('maxlength', $field->getValidatorOption($validator, 'value', ''));
34
                $element->setAttribute('mgmvlength', 'xxxxxxxxxxx');
35
                break;
36
            case Regex::class:
37
                $pattern = $field->getValidatorOption($validator, 'value', '');
38
                if ($pattern[0] === '/' && $pattern[-1] === '/') {
39
                    $pattern = mb_substr($pattern, 1, mb_strlen($pattern) - 2);
40
                }
41
                $element->setAttribute('pattern', $pattern);
42
                break;
43
            default:
44
                break;
45
            }
46
        }
47
48
        return $previous;
49
    }
50
51
    /**
52
     * @param HTMLNode $previous
53
     * @return HTMLNode|null
54
     */
55
    protected function getInput(HTMLNode $previous): ?HTMLNode
56
    {
57
        $input = $previous->get('input');
58
        if (count($input)) {
59
            return $input[0];
60
        }
61
        $input = $previous->get('textarea');
62
        if (count($input)) {
63
            return $input[0];
64
        }
65
        return null;
66
    }
67
}
68