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

MultiSelectRender::renderBlock()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 14
ccs 7
cts 8
cp 0.875
rs 10
cc 3
nc 3
nop 2
crap 3.0175
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