Passed
Push — master ( acf3f9...98cfe3 )
by Derek Stephen
03:04
created

MultiSelectRender   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 93.75%

Importance

Changes 0
Metric Value
wmc 6
eloc 15
c 0
b 0
f 0
dl 0
loc 41
ccs 15
cts 16
cp 0.9375
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A renderBlock() 0 14 3
A processOption() 0 12 3
1
<?php declare(strict_types=1);
2
3
namespace Del\Form\Renderer\Field;
4
5
use Del\Form\Field\FieldInterface;
6
use Del\Form\Field\MultiSelect;
7
use Del\Form\Field\Select;
8
use DOMElement;
9
use InvalidArgumentException;
10
11
class MultiSelectRender extends AbstractFieldRender
12
{
13
    /**
14
     * @param FieldInterface $field
15
     * @param DOMElement $element
16
     * @return DOMElement
17
     */
18 3
    public function renderBlock(FieldInterface $field, DOMElement $element): DOMElement
19
    {
20 3
        if (!$field instanceof MultiSelect) {
21
            throw new InvalidArgumentException('Must be a Del\Form\Field\MultiSelect');
22
        }
23
24 3
        $element->setAttribute('name', $field->getName() . '[]');
25
26 3
        foreach ($field->getOptions() as $value => $label) {
27 3
            $option = $this->processOption($field, $value, $label);
28 3
            $element->appendChild($option);
29
        }
30
31 3
        return $element;
32
    }
33
34
    /**
35
     * @param FieldInterface $field
36
     * @param string $value
37
     * @param string $label
38
     * @return DOMElement
39
     */
40 3
    private function processOption(FieldInterface $field, $value, $label): DOMElement
41
    {
42 3
        $option = $this->createElement('option');
43 3
        $option->setAttribute('value', (string) $value);
44 3
        $label = $this->createText($label);
45 3
        $option->appendChild($label);
46
47 3
        if ($field->getValue() !== null && in_array($option->getAttribute('value'), $field->getValue())) {
48 1
            $option->setAttribute('selected', 'selected');
49
        }
50
51 3
        return $option;
52
    }
53
}
54