HtmlHelper   A
last analyzed

Complexity

Total Complexity 17

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 17
eloc 32
c 1
b 0
f 0
dl 0
loc 64
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A encode() 0 3 1
C buildHtmlAttributes() 0 45 13
A cssStyleFromArray() 0 8 3
1
<?php
2
3
namespace Itstructure\MFU\Helpers;
4
5
/**
6
 * Class HtmlHelper
7
 * @package Itstructure\FMU\Helpers
8
 */
9
class HtmlHelper
10
{
11
    const DATA_ATTRIBUTES = ['data', 'data-ng', 'ng'];
12
13
    public static function buildHtmlAttributes(array $htmlAttributes, string $charset = 'UTF-8'): string
14
    {
15
        $html = '';
16
17
        foreach ($htmlAttributes as $name => $value) {
18
            if (is_bool($value)) {
19
                if ($value) {
20
                    $html .= " $name";
21
                }
22
                continue;
23
            }
24
25
            if (is_array($value)) {
26
                if (in_array($name, self::DATA_ATTRIBUTES)) {
27
                    foreach ($value as $n => $v) {
28
                        if (is_string($v)) {
29
                            $html .= " $name-$n=\"" . self::encode($v, $charset) . '"';
30
                        }
31
                    }
32
                    continue;
33
                }
34
35
                if ($name === 'class') {
36
                    if (empty($value)) {
37
                        continue;
38
                    }
39
                    $html .= " $name=\"" . self::encode(implode(' ', $value), $charset) . '"';
40
                    continue;
41
                }
42
43
                if ($name === 'style') {
44
                    if (empty($value)) {
45
                        continue;
46
                    }
47
                    $html .= " $name=\"" . self::encode(self::cssStyleFromArray($value), $charset) . '"';
48
                }
49
                continue;
50
            }
51
52
            if ($value !== null) {
53
                $html .= " $name=\"" . self::encode($value, $charset) . '"';
54
            }
55
        }
56
57
        return $html;
58
    }
59
60
    public static function encode(string $content, string $charset = 'UTF-8', bool $doubleEncode = true): string
61
    {
62
        return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, $charset, $doubleEncode);
63
    }
64
65
    public static function cssStyleFromArray(array $style): ?string
66
    {
67
        $output = '';
68
        foreach ($style as $name => $value) {
69
            $output .= "$name: $value; ";
70
        }
71
72
        return $output === '' ? null : rtrim($output);
73
    }
74
}
75