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

SelectRender   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 94.12%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 7
eloc 16
c 4
b 0
f 0
dl 0
loc 43
ccs 16
cts 17
cp 0.9412
rs 10

2 Methods

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