isOptionSelected()   A
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 13
rs 9.2222
ccs 0
cts 0
cp 0
cc 6
nc 5
nop 2
crap 42
1
<?php
2
3
class Nip_Form_Renderer_Elements_Select extends \Nip\Form\Renderer\Elements\AbstractElementRenderer
4
{
5
    /**
6
     * @return string
7
     */
8
    public function generateElement()
9
    {
10
        $this->getElement()->addClass('form-select');
11
12
        $return = '<select ';
13
        $return .= $this->renderAttributes();
14
        $return .= ' >' . $this->renderOptions() . '</select>';
15
        return $return;
16
    }
17
18
    public function renderOptions($options = false)
19
    {
20
        $options = $options ? $options : $this->getElement()->getOptions();
21
        $return = '';
22
23
        $selectedValue = $this->getElement()->getValue();
24
25
        foreach ($options as $value=>$atribs) {
26
            if (is_string($value) && !isset($atribs['label'])) {
27
                $return .= '<optgroup label="' . $value . '">';
28
                $return .= $this->renderOptions($atribs);
29
                $return .= '</optgroup>';
30
            } else {
31
                $return .= '<option';
32
33
                $label = $atribs['label'];
34
                unset($atribs['label']);
35
36
                $atribs['value'] = $value;
37
                if ($this->isOptionSelected($value, $selectedValue)) {
38
                    $atribs['selected'] = 'selected';
39
                }
40
41
                foreach ($atribs as $name=>$value) {
0 ignored issues
show
Comprehensibility Bug introduced by
$value is overwriting a variable from outer foreach loop.
Loading history...
42
                    $return .= ' ' . $name . '="' . $value . '"';
43
                }
44
                $return .= '>' . $label . '</option>';
45
            }
46
        }
47
        return $return;
48
    }
49
50
    /**
51
     * @param $value
52
     * @param $selectedValue
53
     * @return bool
54
     */
55
    protected function isOptionSelected($value, $selectedValue): bool
56
    {
57
        if (is_null($selectedValue)) {
58
            return false;
59
        }
60
        if ($selectedValue === 0 or $value === 0) {
61
            if ($value === $selectedValue) {
62
                return true;
63
            }
64
        } elseif ($selectedValue == $value) {
65
            return true;
66
        }
67
        return false;
68
    }
69
}
70