SelectRender::renderBlock()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.0342

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 16
ccs 8
cts 9
cp 0.8889
rs 9.6111
cc 5
nc 5
nop 2
crap 5.0342
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Del\Form\Renderer\Field;
6
7
use Del\Form\Field\FieldInterface;
8
use Del\Form\Field\MultiSelect;
9
use Del\Form\Field\Select;
10
use DOMElement;
11
use InvalidArgumentException;
12
13
class SelectRender extends AbstractFieldRender
14
{
15 5
    public function renderBlock(FieldInterface $field, DOMElement $element): DOMElement
16
    {
17 5
        if (!$field instanceof Select && !$field instanceof MultiSelect) {
18 2
            throw new InvalidArgumentException('Must be a Del\Form\Field\Select or Del\Form\Field\MultiSelect');
19
        }
20
21 3
        if ($field instanceof MultiSelect) {
22
            $element->setAttribute('name', $field->getName() . '[]');
23
        }
24
25 3
        foreach ($field->getOptions() as $value => $label) {
26 3
            $option = $this->processOption($field, $value, $label);
27 3
            $element->appendChild($option);
28
        }
29
30 3
        return $element;
31
    }
32
33 3
    private function processOption(FieldInterface $field, $value, $label): DOMElement
34
    {
35 3
        $option = $this->createElement('option');
36 3
        $option->setAttribute('value', (string) $value);
37 3
        $label = $this->createText($label);
38 3
        $option->appendChild($label);
39
40 3
        if ($field->getValue() == $option->getAttribute('value')) {
41 1
            $option->setAttribute('selected', 'selected');
42
        }
43
44 3
        return $option;
45
    }
46
}
47