Passed
Branch master (3daac1)
by Vincent
07:53
created

SelectHtmlRenderer::render()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.0119

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 20
ccs 10
cts 11
cp 0.9091
rs 9.9332
cc 4
nc 5
nop 2
crap 4.0119
1
<?php
2
3
namespace Bdf\Form\Leaf\View;
4
5
use Bdf\Form\View\FieldViewInterface;
6
use Bdf\Form\View\FieldViewRendererInterface;
7
use Bdf\Form\View\HtmlRenderer;
8
use InvalidArgumentException;
9
10
/**
11
 * Renderer for select element
12
 * Should be used for element with choices
13
 */
14
final class SelectHtmlRenderer implements FieldViewRendererInterface
15
{
16
    /**
17
     * @var SelectHtmlRenderer|null
18
     */
19
    private static $instance;
20
21
    /**
22
     * {@inheritdoc}
23
     */
24 9
    public function render(FieldViewInterface $view, array $attributes): string
25
    {
26 9
        if (!$choices = $view->choices()) {
27
            throw new InvalidArgumentException('Choices must be provided for render a select element.');
28
        }
29
30 9
        $attributes['name'] = $view->name();
31 9
        $attributes['required'] = $view->required();
32
33 9
        if (!empty($attributes['multiple'])) {
34 2
            $attributes['name'] .= '[]';
35
        }
36
37 9
        $options = '';
38
39 9
        foreach ($choices as $choice) {
40 9
            $options .= HtmlRenderer::element('option', ['value' => $choice->value(), 'selected' => $choice->selected()], htmlentities($choice->label()));
41
        }
42
43 9
        return HtmlRenderer::element('select', $attributes, $options);
44
    }
45
46
    /**
47
     * Get the renderer instance
48
     *
49
     * @return self
50
     */
51 17
    public static function instance(): self
52
    {
53 17
        if (self::$instance) {
54 16
            return self::$instance;
55
        }
56
57 1
        return self::$instance = new self;
58
    }
59
}
60