Completed
Push — 7.5 ( a0d1bd...8c0f68 )
by
unknown
25:22
created

DataAttributesExtension::serializeDataAttributes()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
5
 * @license For full copyright and license information view LICENSE file distributed with this source code.
6
 */
7
declare(strict_types=1);
8
9
namespace eZ\Publish\Core\MVC\Symfony\Templating\Twig\Extension;
10
11
use Twig\Extension\AbstractExtension;
12
use Twig\TwigFilter;
13
14
/**
15
 * Twig common extension for general use helpers.
16
 */
17
class DataAttributesExtension extends AbstractExtension
18
{
19
    /**
20
     * Returns a list of functions to add to the existing list.
21
     *
22
     * @return array
23
     */
24
    public function getFilters(): array
25
    {
26
        return [
27
            new TwigFilter(
28
                'ez_data_attributes_serialize',
29
                [$this, 'serializeDataAttributes'],
30
                ['is_safe' => ['html']]
31
            ),
32
        ];
33
    }
34
35
    /**
36
     * Processes an associative list of data attributes and returns them as HTML attributes list
37
     * in the form of <code>data-<attribute_name>="<attribute_value>"</code>.
38
     *
39
     * @param array $dataAttributes
40
     *
41
     * @return string
42
     */
43
    public function serializeDataAttributes(array $dataAttributes): string
44
    {
45
        $result = '';
46
        foreach ($dataAttributes as $attributeName => $attributeValue) {
47
            if (!is_string($attributeValue)) {
48
                $attributeValue = json_encode($attributeValue);
49
            }
50
51
            $result .= sprintf('data-%s="%s" ', $attributeName, htmlspecialchars($attributeValue));
52
        }
53
54
        return rtrim($result);
55
    }
56
}
57