Passed
Pull Request — master (#3)
by Vincent
04:40
created

SelectHtmlRenderer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 15
dl 0
loc 44
ccs 15
cts 15
cp 1
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A instance() 0 7 2
A render() 0 20 4
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 12
    public function render(FieldViewInterface $view, array $attributes): string
25
    {
26 12
        if (!$choices = $view->choices()) {
27 1
            throw new InvalidArgumentException('Choices must be provided for render a select element.');
28
        }
29
30 11
        $attributes['name'] = $view->name();
31 11
        $attributes['required'] = $view->required();
32
33 11
        if (!empty($attributes['multiple'])) {
34 2
            $attributes['name'] .= '[]';
35
        }
36
37 11
        $options = '';
38
39 11
        foreach ($choices as $choice) {
40 11
            $options .= HtmlRenderer::element('option', ['value' => $choice->value(), 'selected' => $choice->selected()], htmlentities($choice->label()));
41
        }
42
43 11
        return HtmlRenderer::element('select', $attributes, $options);
44
    }
45
46
    /**
47
     * Get the renderer instance
48
     *
49
     * @return self
50
     */
51 19
    public static function instance(): self
52
    {
53 19
        if (self::$instance) {
54 18
            return self::$instance;
55
        }
56
57 1
        return self::$instance = new self;
58
    }
59
}
60