HtmlRenderer::attributes()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 17
ccs 9
cts 9
cp 1
rs 10
cc 4
nc 4
nop 1
crap 4
1
<?php
2
3
namespace Bdf\Form\View;
4
5
/**
6
 * Utility for render html elements
7
 */
8
final class HtmlRenderer
9
{
10
    /**
11
     * Render HTML attributes
12
     * The attributes consists of an associative array, with attribute name as key, and string or boolean attributes value as value
13
     * If the value is true, a simple flag is renderer (i.e. attribute without value)
14
     *
15
     * @param array $attributes
16
     *
17
     * @return string
18
     */
19 81
    public static function attributes(array $attributes): string
20
    {
21 81
        $out = '';
22
23 81
        foreach ($attributes as $k => $v) {
24 81
            if ($v === false) {
25 56
                continue;
26
            }
27
28 81
            $out .= ' '.htmlentities($k);
29
30 81
            if ($v !== true) {
31 81
                $out .= '="'.htmlentities((string) $v).'"';
32
            }
33
        }
34
35 81
        return $out;
36
    }
37
38
    /**
39
     * Render an HTML element
40
     * - If $content is null the format is : "< {name} {attributes} />"
41
     * - Else the format is : "< {name} {attributes} > {content} </ {name} >"
42
     *
43
     * @param string $name The element tag name
44
     * @param array $attributes The attributes
45
     * @param string|null $content The element content. If null, a "void element" will be renderer
46
     *
47
     * @return string
48
     */
49 80
    public static function element(string $name, array $attributes, ?string $content = null): string
50
    {
51 80
        if ($content === null) {
52 68
            return '<'.$name.self::attributes($attributes).' />';
53
        }
54
55 15
        return '<'.$name.self::attributes($attributes).'>'.$content.'</'.$name.'>';
56
    }
57
}
58