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

DataAttributesExtension   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 40
rs 10
c 0
b 0
f 0
wmc 4
lcom 0
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getFilters() 0 10 1
A serializeDataAttributes() 0 13 3
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