• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

heimrichhannot / contao-utils-bundle / 12652692899

07 Jan 2025 01:37PM UTC coverage: 25.175% (+0.02%) from 25.158%
12652692899

push

github

web-flow
feature/backport generate data attributes string options (#91)

* backport GenerateDataAttributesStringOptions

* update workflows

* fixed phpstan issue

7 of 25 new or added lines in 2 files covered. (28.0%)

1477 of 5867 relevant lines covered (25.17%)

1.56 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

81.13
/src/Util/Html/HtmlUtil.php
1
<?php
2

3
/*
4
 * Copyright (c) 2023 Heimrich & Hannot GmbH
5
 *
6
 * @license LGPL-3.0-or-later
7
 */
8

9
namespace HeimrichHannot\UtilsBundle\Util\Html;
10

11
use HeimrichHannot\UtilsBundle\Util\HtmlUtil\GenerateDataAttributesStringOptions;
12
use function Symfony\Component\String\u;
13

14
class HtmlUtil
15
{
16
    /**
17
     * Generate a attribute string for html elements out of an array.
18
     *
19
     * Options:
20
     * - xhtml: (bool) XHTML format instead of HTML5 format. Default false
21
     */
22
    public function generateAttributeString(array $attributes, array $options = []): string
23
    {
24
        $options = array_merge([
4✔
25
            'xhtml' => false,
4✔
26
        ], $options);
4✔
27

28
        return trim(implode(' ', array_map(function ($key) use ($attributes, $options) {
4✔
29
            if (\is_bool($attributes[$key])) {
4✔
30
                if ($options['xhtml']) {
2✔
31
                    return $attributes[$key] ? sprintf('%s="%s"', $key, $key) : '';
1✔
32
                }
33

34
                return $attributes[$key] ? $key : '';
2✔
35
            }
36

37
            return $key.'="'.$attributes[$key].'"';
4✔
38
        }, array_keys($attributes))));
4✔
39
    }
40

41
    /**
42
     * Generates a data-attributes string out of an array.
43
     *
44
     * @param array{
45
     *     xhtml?: bool,
46
     *     normalizeKeys?: bool,
47
     *     array_handling?: 'reduce'|'encode',
48
     * }|GenerateDataAttributesStringOptions $options (GenerateDataAttributesStringOptions is only supported from php 8.1)
49
     *
50
     * Options (additional to Options from HtmlUtl::generateAttributeString()):
51
     * - normalizeKeys: Array keys are normalized to lowercase dash-cased strings (e.g. Foo Bar_player is transformed to foo-bar-player)
52
     */
53
    public function generateDataAttributesString(array $attributes, $options = []): string
54
    {
55
        if ($options instanceof GenerateDataAttributesStringOptions) {
1✔
NEW
56
            if (version_compare(phpversion(), '8.1', '<')) {
×
NEW
57
                throw new \InvalidArgumentException('Argument $options must be an array for php versions < 8.1');
×
58
            }
59

NEW
60
            $options = [
×
NEW
61
                'xhtml' => $options->isXhtml(),
×
NEW
62
                'normalizeKeys' => $options->isNormalizeKeys(),
×
NEW
63
                'array_handling' => $options->getArrayHandling()->value,
×
NEW
64
            ];
×
65
        } elseif (is_array($options)) {
1✔
66
            $options = array_merge([
1✔
67
                'xhtml' => false,
1✔
68
                'normalizeKeys' => true,
1✔
69
                'array_handling' => 'reduce',
1✔
70
            ], $options);
1✔
71
        } else {
NEW
72
            throw new \InvalidArgumentException('Argument $options must be an array or an instance of GenerateDataAttributesStringOptions');
×
73
        }
74

75
        if (!\in_array($options['array_handling'], ['reduce', 'encode'])) {
1✔
76
            $options['array_handling'] = 'reduce';
1✔
77
        }
78

79
        $dataAttributes = [];
1✔
80

81
        foreach ($attributes as $key => $value) {
1✔
82
            if (false === $value) {
1✔
83
                continue;
1✔
84
            }
85

86
            if (\is_array($value)) {
1✔
87
                if ('reduce' === $options['array_handling']) {
1✔
88
                    $value = implode(' ', array_reduce($value, function ($tokens, $token) {
1✔
89
                        if (\is_string($token)) {
1✔
90
                            $token = trim($token);
1✔
91

92
                            if (\strlen($token) > 0) {
1✔
93
                                $tokens[] = $token;
1✔
94
                            }
95
                        } elseif (is_numeric($token)) {
×
96
                            $tokens[] = $token;
×
97
                        }
98

99
                        return $tokens;
1✔
100
                    }, []));
1✔
101

102
                    if (empty($value)) {
1✔
103
                        continue;
1✔
104
                    }
105
                } elseif ('encode' === $options['array_handling']) {
1✔
106
                    $value = htmlspecialchars(json_encode($value), \ENT_QUOTES, 'UTF-8');
1✔
107
                }
108
            }
109

110
            if ($options['normalizeKeys']) {
1✔
111
                $key = str_replace('_', '-', u($key)->snake());
1✔
112
            }
113

114
            if (!str_starts_with($key, 'data-')) {
1✔
115
                $key = 'data-'.$key;
1✔
116
            }
117

118
            $dataAttributes[$key] = $value;
1✔
119
        }
120

121
        unset($options['normalizeKeys']);
1✔
122

123
        return $this->generateAttributeString($dataAttributes, $options);
1✔
124
    }
125
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc