File: HtmlAttrTest.php

package info (click to toggle)
php-twig 3.24.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,620 kB
  • sloc: php: 26,096; makefile: 123; sh: 43
file content (318 lines) | stat: -rw-r--r-- 9,387 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
<?php

/*
 * This file is part of Twig.
 *
 * (c) Fabien Potencier
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Twig\Extra\Html\Tests;

use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Twig\Environment;
use Twig\Error\RuntimeError;
use Twig\Extra\Html\HtmlAttr\AttributeValueInterface;
use Twig\Extra\Html\HtmlAttr\SeparatedTokenList;
use Twig\Extra\Html\HtmlExtension;
use Twig\Loader\ArrayLoader;

class HtmlAttrTest extends TestCase
{
    #[DataProvider('htmlAttrProvider')]
    public function testPrintingAttributes(string $expected, array $inputs)
    {
        $result = HtmlExtension::htmlAttr(new Environment(new ArrayLoader()), ...$inputs);

        self::assertEquals($expected, $result);
    }

    public static function htmlAttrProvider(): \Generator
    {
        yield 'merging from variadic arguments; ignoring null, false and empty string values' => [
            'id="some-id" label="some-label" role="main"',
            [
                ['id' => 'some-id'],
                null,
                '',
                false,
                ['label' => 'some-label'],
                ['role' => 'main'],
            ],
        ];

        // Boolean attribute handling
        yield 'boolean true renders as empty string, except for aria-* and data-* it uses "true"' => [
            'required="" aria-disabled="true" data-yes="true"',
            [
                ['required' => true, 'aria-disabled' => true, 'data-yes' => true],
            ],
        ];

        yield 'boolean false omits attribute, except for aria-* it uses "false"' => [
            'aria-disabled="false"',
            [
                ['disabled' => false, 'aria-disabled' => false, 'data-gone' => false],
            ],
        ];

        yield 'null value omits attribute, also for special cases' => [
            '',
            [
                ['title' => null, 'style' => null, 'aria-gone' => null, 'data-nil' => null],
            ],
        ];

        yield 'empty string renders as empty attribute value' => [
            'title=""',
            [
                ['title' => ''],
            ],
        ];

        // Data attributes
        yield 'data attribute with array is JSON encoded' => [
            'data-config="{&quot;theme&quot;:&quot;dark&quot;}"',
            [
                ['data-config' => ['theme' => 'dark']],
            ],
        ];

        // In general, array values are printed as space-separated token lists
        yield 'array value renders as space-separated token list' => [
            'class="btn btn-primary btn-lg"',
            [
                ['class' => ['btn', 'btn-primary', 'btn-lg']],
            ],
        ];

        yield 'arrays with just an empty string produce the empty attribute' => [
            'foo=""',
            [
                ['foo' => ['']],
            ],
        ];

        yield 'arrays with just a true value produce the empty attribute' => [
            'foo=""',
            [
                ['foo' => [true]],
            ],
        ];

        yield 'arrays with just a null value are not printed' => [
            '',
            [
                ['foo' => [null]],
            ],
        ];

        // Style attributes
        yield 'style with plain string value' => [
            'style="color: red;"',
            [
                ['style' => 'color: red;'],
            ],
        ];

        yield 'style with associative array' => [
            'style="color: red; font-size: 16px;"',
            [
                ['style' => ['color' => 'red', 'font-size' => '16px']],
            ],
        ];

        yield 'style with numeric array' => [
            'style="color: red; font-size: 16px;"',
            [
                ['style' => ['color: red', 'font-size: 16px']],
            ],
        ];

        yield 'merging style attributes overrides by key' => [
            'style="color: blue; font-size: 14px;"',
            [
                ['style' => ['color' => 'red', 'font-size' => '14px']],
                ['style' => ['color' => 'blue']],
            ],
        ];

        // Escaping
        yield 'attribute name is escaped' => [
            'data-user&#x20;id="123"',
            [
                ['data-user id' => '123'],
            ],
        ];

        yield 'attribute value is escaped' => [
            'title="&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;"',
            [
                ['title' => '<script>alert("xss")</script>'],
            ],
        ];

        // Variadic merging scenarios
        yield 'scalar value overrides from left to right' => [
            'id="final"',
            [
                ['id' => 'first'],
                ['id' => 'second'],
                ['id' => 'final'],
            ],
        ];

        yield 'variadic with mixed false and null values' => [
            'id="test"',
            [
                ['id' => 'test'],
                null,
                false,
                null,
            ],
        ];

        yield 'variadic with empty arrays' => [
            'id="test"',
            [
                [],
                ['id' => 'test'],
                [],
            ],
        ];

        yield 'variadic with empty string values' => [
            'id="test"',
            [
                '',
                ['id' => 'test'],
                '',
            ],
        ];

        // AttributeValueInterface
        yield 'AttributeValueInterface with string value' => [
            'custom="custom-value"',
            [
                ['custom' => new AttributeValueStub('custom-value')],
            ],
        ];

        yield 'AttributeValueInterface with null value omits attribute' => [
            '',
            [
                ['custom' => new AttributeValueStub(null)],
            ],
        ];

        yield 'AttributeValueInterface wins over special case handling for style and data-*' => [
            'style="some style" data-custom="not JSON"',
            [
                ['style' => new AttributeValueStub('some style'), 'data-custom' => new AttributeValueStub('not JSON')],
            ],
        ];

        // Edge cases
        yield 'numeric attribute value' => [
            'tabindex="0"',
            [
                ['tabindex' => 0],
            ],
        ];

        yield 'zero is not treated as falsy' => [
            'data-count="0"',
            [
                ['data-count' => 0],
            ],
        ];

        // Scalar and object merging in rendering
        yield 'string replaces object in rendering' => [
            'value="new-string"',
            [
                ['value' => new \stdClass()],
                ['value' => 'new-string'],
            ],
        ];

        yield 'object replaces string in rendering uses __toString if available' => [
            'value="stringable-object"',
            [
                ['value' => 'old-string'],
                ['value' => new StringableStub('stringable-object')],
            ],
        ];
    }

    public function testIterableObjectCastedToArray()
    {
        /*
            This test case demonstrates how objects could e. g. implement helper logic
            to construct more complex attribute combinations and sets, and be passed as
            one argument to html_attr as well.
        */
        $object = new class implements \IteratorAggregate {
            public function getIterator(): \Traversable
            {
                return new \ArrayIterator([
                    'data-controller' => new SeparatedTokenList(['dropdown', 'tooltip']),
                    'data-action' => new SeparatedTokenList(['click->dropdown#toggle', 'mouseover->tooltip#show']),
                ]);
            }
        };

        $result = HtmlExtension::htmlAttr(new Environment(new ArrayLoader()), $object);

        self::assertSame('data-controller="dropdown tooltip" data-action="click-&gt;dropdown#toggle mouseover-&gt;tooltip#show"', $result);
    }

    public function testDataAttributeWithNonJsonEncodableValueThrowsRuntimeError()
    {
        $this->expectException(RuntimeError::class);
        $this->expectExceptionMessage('The "data-bad" attribute value cannot be JSON encoded.');

        HtmlExtension::htmlAttr(
            new Environment(new ArrayLoader()),
            ['data-bad' => [\INF]]  // INF cannot be JSON-encoded
        );
    }

    public function testNonStringableObjectAsAttributeValueThrowsRuntimeError()
    {
        $this->expectException(RuntimeError::class);
        $this->expectExceptionMessage('The "title" attribute value should be a scalar, an iterable, or an object implementing "Stringable"');

        HtmlExtension::htmlAttr(
            new Environment(new ArrayLoader()),
            ['title' => new \stdClass()]
        );
    }
}

class StringableStub implements \Stringable
{
    public function __construct(private readonly string $value)
    {
    }

    public function __toString(): string
    {
        return $this->value;
    }
}

class AttributeValueStub implements AttributeValueInterface
{
    public function __construct(private readonly ?string $value)
    {
    }

    public function getValue(): ?string
    {
        return $this->value;
    }
}