-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockFactory.php
More file actions
657 lines (571 loc) · 27.5 KB
/
Copy pathBlockFactory.php
File metadata and controls
657 lines (571 loc) · 27.5 KB
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
<?php
declare(strict_types=1);
namespace Automattic\BlocksEngine\PhpTransformer\HtmlToBlocks;
use Automattic\BlocksEngine\PhpTransformer\HtmlToBlocks\Style\StyleAttributeMapper;
/**
* @internal Block construction is owned by HtmlTransformer.
*/
final class BlockFactory
{
/**
* Semantic container tags `core/group` may render as its wrapper element.
* `div` is the canonical default; the rest mirror the semantic HTML5
* landmarks core's group block exposes via its `tagName` attribute.
*
* @var array<int, string>
*/
private const GROUP_TAG_NAMES = array( 'div', 'header', 'nav', 'section', 'article', 'aside', 'footer', 'main' );
private ?StyleAttributeMapper $styleMapper = null;
private function styleMapper(): StyleAttributeMapper
{
return $this->styleMapper ??= new StyleAttributeMapper();
}
/**
* @param array<string, mixed> $attrs
* @param array<int, array<string, mixed>> $innerBlocks
* @return array<string, mixed>
*/
public function create(string $name, array $attrs = array(), array $innerBlocks = array()): array
{
$attrs = $this->normalizeAttrsForBlock($name, $attrs);
$innerHtml = $this->blockHtml($name, $attrs, $innerBlocks);
if ( is_array($innerHtml) ) {
$innerContent = array( $innerHtml['opening'] );
foreach ( $innerBlocks as $_ ) {
$innerContent[] = null;
}
$innerContent[] = $innerHtml['closing'];
$innerHtml = $innerHtml['opening'] . $innerHtml['closing'];
} else {
$innerContent = array( $innerHtml );
}
return array(
'blockName' => $name,
'attrs' => $this->commentAttrs($name, $attrs),
'innerBlocks' => $innerBlocks,
'innerHTML' => $innerHtml,
'innerContent' => $innerContent,
);
}
/**
* @param array<string, mixed> $attrs
* @return array<string, mixed>
*/
private function normalizeAttrsForBlock(string $name, array $attrs): array
{
if ( in_array($name, array( 'core/buttons', 'core/column', 'core/columns', 'core/group', 'core/heading', 'core/list-item', 'core/paragraph' ), true) ) {
unset($attrs['style']['spacing']['blockGap']);
if ( empty($attrs['style']['spacing']) ) {
unset($attrs['style']['spacing']);
}
if ( empty($attrs['style']) ) {
unset($attrs['style']);
}
}
return $attrs;
}
/**
* @param array<string, mixed> $attrs
* @return array<string, mixed>
*/
private function commentAttrs(string $name, array $attrs): array
{
if ( 'core/paragraph' === $name && preg_match('/^\s*<a\b/i', (string) ($attrs['content'] ?? '')) ) {
unset($attrs['content']);
}
return $attrs;
}
/**
* @param array<string, mixed> $attrs
* @param array<int, array<string, mixed>> $innerBlocks
* @return string|array{opening: string, closing: string}
*/
private function blockHtml(string $name, array $attrs, array $innerBlocks): string|array
{
if ( 'core/heading' === $name ) {
$level = (int) ($attrs['level'] ?? 2);
$level = max(1, min(6, $level));
return '<h' . $level . $this->blockSupportAttrs($attrs, 'wp-block-heading') . '>' . ($attrs['content'] ?? '') . '</h' . $level . '>';
}
if ( 'core/paragraph' === $name ) {
return '<p' . $this->blockSupportAttrs($attrs) . '>' . ($attrs['content'] ?? '') . '</p>';
}
if ( 'core/list-item' === $name ) {
if ( array() !== $innerBlocks ) {
return array( 'opening' => '<li' . $this->blockSupportAttrs($attrs) . '>' . ($attrs['content'] ?? ''), 'closing' => '</li>' );
}
return '<li' . $this->blockSupportAttrs($attrs) . '>' . ($attrs['content'] ?? '') . '</li>';
}
if ( 'core/list' === $name ) {
$tagName = ! empty($attrs['ordered']) ? 'ol' : 'ul';
return array( 'opening' => '<' . $tagName . $this->blockSupportAttrs($attrs, 'wp-block-list') . '>', 'closing' => '</' . $tagName . '>' );
}
if ( 'core/quote' === $name ) {
$closing = '' !== ($attrs['citation'] ?? '') ? '<cite>' . $attrs['citation'] . '</cite></blockquote>' : '</blockquote>';
return array( 'opening' => '<blockquote' . $this->blockSupportAttrs($attrs, 'wp-block-quote') . '>', 'closing' => $closing );
}
if ( 'core/pullquote' === $name ) {
$citation = '' !== ($attrs['citation'] ?? '') ? '<cite>' . $attrs['citation'] . '</cite>' : '';
return '<figure' . $this->blockSupportAttrs($attrs, 'wp-block-pullquote') . '><blockquote>' . ($attrs['value'] ?? '') . $citation . '</blockquote></figure>';
}
if ( 'core/code' === $name ) {
$content = (string) ($attrs['content'] ?? '');
if ( ! preg_match('/<(?:span|mark|b|strong|i|em)\b/i', $content) ) {
$content = htmlspecialchars($content, ENT_NOQUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
return '<pre class="wp-block-code"><code>' . $content . '</code></pre>';
}
if ( 'core/math' === $name ) {
return '<div' . $this->blockSupportAttrs($attrs, 'wp-block-math') . '>' . ($attrs['content'] ?? '') . '</div>';
}
if ( 'core/icon' === $name ) {
$support = $this->styleSupport($attrs['style'] ?? null);
$iconAttrs = array(
'class' => $this->mergeClassNames('wp-block-icon', $support['classes'], (string) ($attrs['className'] ?? '')),
'style' => $support['style'],
'aria-label' => (string) ($attrs['label'] ?? ''),
'aria-hidden' => ! empty($attrs['ariaHidden']) ? 'true' : '',
);
return '<div' . $this->htmlAttrs($iconAttrs) . '>' . ($attrs['svg'] ?? '') . '</div>';
}
if ( 'core/preformatted' === $name ) {
return '<pre' . $this->blockSupportAttrs($attrs, 'wp-block-preformatted') . '>' . ($attrs['content'] ?? '') . '</pre>';
}
if ( 'core/table' === $name ) {
return $this->tableHtml($attrs);
}
if ( 'core/separator' === $name ) {
return '<hr' . $this->blockSupportAttrs($attrs, 'wp-block-separator') . ' />';
}
if ( 'core/spacer' === $name ) {
$height = (string) ($attrs['height'] ?? '');
$style = trim('' !== $height ? 'height:' . $height : (string) ($attrs['style'] ?? ''));
$attrs['style'] = $style;
return '<div' . $this->blockSupportAttrs($attrs, 'wp-block-spacer') . ' aria-hidden="true"></div>';
}
if ( 'core/columns' === $name ) {
return array( 'opening' => '<div' . $this->blockSupportAttrs($attrs, 'wp-block-columns') . '>', 'closing' => '</div>' );
}
if ( 'core/column' === $name ) {
return array( 'opening' => '<div' . $this->blockSupportAttrs($attrs, 'wp-block-column') . '>', 'closing' => '</div>' );
}
if ( 'core/details' === $name ) {
return array(
'opening' => '<details' . $this->blockSupportAttrs($attrs, 'wp-block-details') . '><summary>' . ($attrs['summary'] ?? '') . '</summary>',
'closing' => '</details>',
);
}
if ( 'core/accordion' === $name ) {
return array( 'opening' => '<div' . $this->blockSupportAttrs($attrs, 'wp-block-accordion') . '>', 'closing' => '</div>' );
}
if ( 'core/accordion-item' === $name ) {
$attrs['className'] = $this->mergeClassNames((string) ($attrs['className'] ?? ''), ! empty($attrs['openByDefault']) ? 'is-open' : '');
return array( 'opening' => '<div' . $this->blockSupportAttrs($attrs, 'wp-block-accordion-item') . '>', 'closing' => '</div>' );
}
if ( 'core/accordion-heading' === $name ) {
$level = (int) ($attrs['level'] ?? 3);
$level = max(1, min(6, $level));
return '<h' . $level . $this->blockSupportAttrs($attrs, 'wp-block-accordion-heading') . '><button type="button" class="wp-block-accordion-heading__toggle"><span class="wp-block-accordion-heading__toggle-title">' . ($attrs['title'] ?? '') . '</span></button></h' . $level . '>';
}
if ( 'core/accordion-panel' === $name ) {
return array( 'opening' => '<div' . $this->blockSupportAttrs($attrs, 'wp-block-accordion-panel') . '>', 'closing' => '</div>' );
}
if ( 'core/image' === $name ) {
return $this->imageHtml($attrs);
}
if ( 'core/gallery' === $name ) {
$caption = ! empty($attrs['caption']) ? '<figcaption class="blocks-gallery-caption wp-element-caption">' . $attrs['caption'] . '</figcaption>' : '';
return array( 'opening' => '<figure' . $this->blockSupportAttrs($attrs, 'wp-block-gallery') . '>', 'closing' => $caption . '</figure>' );
}
if ( 'core/embed' === $name ) {
return $this->embedHtml($attrs);
}
if ( 'core/file' === $name ) {
return $this->fileHtml($attrs);
}
if ( 'core/video' === $name ) {
return $this->mediaHtml('video', $attrs);
}
if ( 'core/audio' === $name ) {
return $this->mediaHtml('audio', $attrs);
}
if ( 'core/search' === $name ) {
return $this->searchHtml($attrs);
}
if ( 'core/html' === $name ) {
return (string) ($attrs['content'] ?? '');
}
if ( 'core/buttons' === $name ) {
return array( 'opening' => '<div' . $this->blockSupportAttrs($attrs, 'wp-block-buttons') . '>', 'closing' => '</div>' );
}
if ( 'core/button' === $name ) {
$support = $this->buttonStyleSupport($attrs);
// Match core/button save(): useBlockProps.save() lives on the OUTER
// wrapper <div>, so the block className and the anchor id belong on
// the wrapper. The inner <a>/<button> carries only the structural
// wp-block-button__link / wp-element-button classes plus color and
// border support classes/styles. Routing the source className onto
// the inner element instead leaves the stored markup divergent from
// save() and the editor flags the block invalid.
$wrapperAttrs = array(
'id' => (string) ($attrs['anchor'] ?? ''),
'class' => $this->mergeClassNames('wp-block-button', (string) ($attrs['className'] ?? '')),
);
if ( 'button' === ($attrs['tagName'] ?? '') ) {
$buttonAttrs = array_intersect_key($attrs, array_flip(array( 'type', 'role', 'aria-label', 'aria-controls', 'aria-expanded', 'aria-haspopup' )));
foreach ( $attrs as $attrName => $attrValue ) {
if ( is_string($attrName) && str_starts_with(strtolower($attrName), 'data-') ) {
$buttonAttrs[$attrName] = (string) $attrValue;
}
}
$buttonAttrs = array_merge(array(
'class' => $this->mergeClassNames('wp-block-button__link', $support['classes'], 'wp-element-button'),
'style' => $support['style'],
), $buttonAttrs);
return '<div' . $this->htmlAttrs($wrapperAttrs) . '><button' . $this->htmlAttrs($buttonAttrs) . '>' . ($attrs['text'] ?? '') . '</button></div>';
}
$href = '' !== ($attrs['url'] ?? '') ? ' href="' . htmlspecialchars((string) $attrs['url'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '"' : '';
$linkAttrs = array(
'class' => $this->mergeClassNames('wp-block-button__link', $support['classes'], 'wp-element-button'),
'style' => $support['style'],
);
return '<div' . $this->htmlAttrs($wrapperAttrs) . '><a' . $this->htmlAttrs($linkAttrs) . $href . '>' . ($attrs['text'] ?? '') . '</a></div>';
}
// The navigation family (`core/navigation`, `core/navigation-link`,
// `core/navigation-submenu`) are dynamic, server-rendered blocks:
// `supports.html` is false and each registers a `render_callback`, so
// their `save()` returns null. WordPress stores only the block comment
// delimiters (plus serialized inner blocks); the `<nav>`/`<ul>`/`<li>`
// chrome is produced at render time. Emitting that static markup into the
// stored block makes `wp.blocks.validateBlock` re-run `save()` (empty),
// see the leftover tags, and flag every navigation block invalid in the
// editor. The label/url/className ride in the comment attributes, so the
// canonical save()-matching shape carries no inner HTML at all.
if ( 'core/navigation' === $name || 'core/navigation-submenu' === $name ) {
return array( 'opening' => '', 'closing' => '' );
}
if ( 'core/navigation-link' === $name ) {
return '';
}
if ( 'core/shortcode' === $name ) {
return '<div class="wp-block-shortcode">' . ($attrs['text'] ?? '') . '</div>';
}
if ( 'core/group' === $name ) {
$tag = $this->groupTagName($attrs['tagName'] ?? null);
return array( 'opening' => '<' . $tag . $this->blockSupportAttrs($attrs, 'wp-block-group') . '>', 'closing' => '</' . $tag . '>' );
}
return '';
}
/**
* Resolve the wrapper tag for a `core/group`. Core's group `save()` renders
* `<TagName>` from the `tagName` attribute, defaulting to `div`. Only the
* semantic container tags core treats as group wrappers are honored; any
* other value falls back to `div` so output never diverges from `save()`.
*/
private function groupTagName(mixed $tagName): string
{
return is_string($tagName) && in_array($tagName, self::GROUP_TAG_NAMES, true) ? $tagName : 'div';
}
/**
* @param array<string, mixed> $attrs
*/
private function tableHtml(array $attrs): string
{
$html = '<figure' . $this->blockSupportAttrs($attrs, 'wp-block-table') . '><table>';
foreach ( array( 'head' => 'thead', 'body' => 'tbody', 'foot' => 'tfoot' ) as $attrName => $tagName ) {
if ( empty($attrs[$attrName]) || ! is_array($attrs[$attrName]) ) {
continue;
}
$html .= '<' . $tagName . '>';
foreach ( $attrs[$attrName] as $row ) {
$html .= '<tr>';
foreach ( $row['cells'] ?? array() as $cell ) {
$cellTag = 'th' === ($cell['tag'] ?? '') ? 'th' : 'td';
$html .= '<' . $cellTag . '>' . ($cell['content'] ?? '') . '</' . $cellTag . '>';
}
$html .= '</tr>';
}
$html .= '</' . $tagName . '>';
}
$html .= '</table>';
if ( ! empty($attrs['caption']) ) {
$html .= '<figcaption class="wp-element-caption">' . $attrs['caption'] . '</figcaption>';
}
return $html . '</figure>';
}
/**
* @param array<string, mixed> $attrs
*/
private function imageHtml(array $attrs): string
{
$figureAttrs = $attrs;
if ( ! empty($attrs['sizeSlug']) ) {
$figureAttrs['className'] = $this->mergeClassNames((string) ($figureAttrs['className'] ?? ''), 'size-' . (string) $attrs['sizeSlug']);
}
$imageAttrs = array(
'src' => $attrs['url'] ?? '',
'alt' => $attrs['alt'] ?? '',
'title' => $attrs['title'] ?? '',
'srcset' => $attrs['srcset'] ?? '',
'sizes' => $attrs['sizes'] ?? '',
'width' => (string) ($attrs['width'] ?? ''),
'height' => (string) ($attrs['height'] ?? ''),
'class' => ! empty($attrs['id']) ? 'wp-image-' . (string) $attrs['id'] : '',
);
$img = '<img' . $this->htmlAttrs($imageAttrs, array( 'alt' )) . '/>';
if ( ! empty($attrs['href']) ) {
$linkAttrs = array(
'href' => (string) $attrs['href'],
'id' => (string) ($attrs['linkAnchor'] ?? ''),
'target' => (string) ($attrs['linkTarget'] ?? ''),
'rel' => (string) ($attrs['rel'] ?? ''),
'class' => (string) ($attrs['linkClass'] ?? ''),
'aria-label' => (string) ($attrs['linkAriaLabel'] ?? ''),
'aria-hidden' => (string) ($attrs['linkAriaHidden'] ?? ''),
'tabindex' => (string) ($attrs['linkTabIndex'] ?? ''),
);
$img = '<a' . $this->htmlAttrs($linkAttrs) . '>' . $img . '</a>';
}
$caption = ! empty($attrs['caption']) ? '<figcaption class="wp-element-caption">' . $attrs['caption'] . '</figcaption>' : '';
return '<figure' . $this->blockSupportAttrs($figureAttrs, 'wp-block-image') . '>' . $img . $caption . '</figure>';
}
/**
* @param array<string, mixed> $attrs
*/
private function embedHtml(array $attrs): string
{
$url = htmlspecialchars((string) ($attrs['url'] ?? ''), ENT_NOQUOTES | ENT_SUBSTITUTE, 'UTF-8');
$classes = array('wp-block-embed');
if ( ! empty($attrs['type']) ) {
$classes[] = 'is-type-' . (string) $attrs['type'];
}
if ( ! empty($attrs['providerNameSlug']) ) {
$classes[] = 'is-provider-' . (string) $attrs['providerNameSlug'];
$classes[] = 'wp-block-embed-' . (string) $attrs['providerNameSlug'];
}
$figureAttrs = $attrs;
$figureAttrs['className'] = $this->mergeClassNames(implode(' ', $classes), (string) ($attrs['className'] ?? ''));
return '<figure' . $this->blockSupportAttrs($figureAttrs) . '><div class="wp-block-embed__wrapper">' . $url . '</div></figure>';
}
/**
* @param array<string, mixed> $attrs
*/
private function fileHtml(array $attrs): string
{
$href = (string) ($attrs['href'] ?? $attrs['url'] ?? '');
$text = (string) ($attrs['text'] ?? ($href !== '' ? basename(parse_url($href, PHP_URL_PATH) ?: $href) : ''));
$linkAttrs = array(
'href' => $href,
);
$downloadButton = '';
if ( ! empty($attrs['showDownloadButton']) ) {
$downloadButton = '<a class="wp-block-file__button wp-element-button" href="' . htmlspecialchars($href, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '" download>Download</a>';
}
return '<div' . $this->blockSupportAttrs($attrs, 'wp-block-file') . '><a' . $this->htmlAttrs($linkAttrs) . '>' . $text . '</a>' . $downloadButton . '</div>';
}
/**
* @param array<string, mixed> $attrs
*/
private function mediaHtml(string $tagName, array $attrs): string
{
$mediaAttrs = array(
'src' => (string) ($attrs['src'] ?? ''),
'poster' => (string) ($attrs['poster'] ?? ''),
'preload' => (string) ($attrs['preload'] ?? ''),
'width' => (string) ($attrs['width'] ?? ''),
'height' => (string) ($attrs['height'] ?? ''),
'controls' => ! empty($attrs['controls']) ? 'controls' : '',
);
$caption = ! empty($attrs['caption']) ? '<figcaption class="wp-element-caption">' . $attrs['caption'] . '</figcaption>' : '';
return '<figure' . $this->blockSupportAttrs($attrs, 'wp-block-' . $tagName) . '><' . $tagName . $this->htmlAttrs($mediaAttrs) . '></' . $tagName . '>' . $caption . '</figure>';
}
/**
* @param array<string, mixed> $attrs
*/
private function searchHtml(array $attrs): string
{
$inputId = (string) ($attrs['inputAnchor'] ?? '');
$label = (string) ($attrs['label'] ?? 'Search');
$labelAttrs = array(
'class' => 'wp-block-search__label',
'for' => $inputId,
);
$inputAttrs = array(
'type' => 'search',
'id' => $inputId,
'class' => $this->mergeClassNames('wp-block-search__input', (string) ($attrs['inputClassName'] ?? '')),
'name' => 's',
'placeholder' => (string) ($attrs['placeholder'] ?? ''),
);
$buttonText = (string) ($attrs['buttonText'] ?? 'Search');
$button = '' !== trim($buttonText) ? '<button type="submit" class="wp-block-search__button wp-element-button">' . $buttonText . '</button>' : '';
return '<form role="search" method="get"' . $this->blockSupportAttrs($attrs, 'wp-block-search') . '><label' . $this->htmlAttrs($labelAttrs) . '>' . $label . '</label><div class="wp-block-search__inside-wrapper"><input' . $this->htmlAttrs($inputAttrs) . ' />' . $button . '</div></form>';
}
/**
* Translate a core/button block's native style support into the rendered
* has-* support classes and the inline style string WordPress emits for
* custom colors and borders. Accepts the canonical `style` object; falls back
* to a legacy raw `style` string when present for backward compatibility.
*
* @param array<string, mixed> $attrs
* @return array{classes: string, style: string}
*/
private function buttonStyleSupport(array $attrs): array
{
$style = $attrs['style'] ?? null;
if ( ! is_array($style) ) {
return array(
'classes' => '',
'style' => is_string($style) ? $style : '',
);
}
$classes = array();
$declarations = array();
$background = (string) ($style['color']['background'] ?? '');
$text = (string) ($style['color']['text'] ?? '');
if ( '' !== $text ) {
$classes[] = 'has-text-color';
$declarations[] = 'color:' . $text;
}
if ( '' !== $background ) {
$classes[] = 'has-background';
$declarations[] = 'background-color:' . $background;
}
$border = is_array($style['border'] ?? null) ? $style['border'] : array();
if ( isset($border['color']) && '' !== (string) $border['color'] ) {
$classes[] = 'has-border-color';
$declarations[] = 'border-color:' . (string) $border['color'];
}
if ( isset($border['width']) && '' !== (string) $border['width'] ) {
$declarations[] = 'border-width:' . (string) $border['width'];
}
if ( isset($border['style']) && '' !== (string) $border['style'] ) {
$declarations[] = 'border-style:' . (string) $border['style'];
}
if ( isset($border['radius']) && '' !== (string) $border['radius'] ) {
$declarations[] = 'border-radius:' . (string) $border['radius'];
}
$padding = is_array($style['spacing']['padding'] ?? null) ? $style['spacing']['padding'] : array();
foreach ( array( 'top', 'right', 'bottom', 'left' ) as $side ) {
if ( isset($padding[$side]) && '' !== (string) $padding[$side] ) {
$declarations[] = 'padding-' . $side . ':' . (string) $padding[$side];
}
}
$typography = is_array($style['typography'] ?? null) ? $style['typography'] : array();
if ( isset($typography['fontSize']) && '' !== (string) $typography['fontSize'] ) {
$classes[] = 'has-custom-font-size';
}
$typographyMap = array(
'fontSize' => 'font-size',
'fontWeight' => 'font-weight',
'lineHeight' => 'line-height',
'textTransform' => 'text-transform',
);
foreach ( $typographyMap as $attrName => $cssName ) {
if ( isset($typography[$attrName]) && '' !== (string) $typography[$attrName] ) {
$declarations[] = $cssName . ':' . (string) $typography[$attrName];
}
}
return array(
'classes' => implode(' ', $classes),
'style' => implode(';', $declarations),
);
}
private function mergeClassNames(string ...$classNames): string
{
$classes = array();
foreach ( $classNames as $className ) {
foreach ( preg_split('/\s+/', trim($className)) ?: array() as $class ) {
if ( '' !== $class && ! in_array($class, $classes, true) ) {
$classes[] = $class;
}
}
}
return implode(' ', $classes);
}
/**
* @param array<string, mixed> $attrs
*/
private function blockSupportAttrs(array $attrs, string $baseClass = ''): string
{
$support = $this->styleSupport($attrs['style'] ?? null);
$presetClasses = $this->presetColorClasses($attrs);
$layoutClasses = $this->layoutClasses($attrs['layout'] ?? null, $baseClass);
$classes = $this->mergeClassNames($baseClass, $presetClasses, $support['classes'], $layoutClasses, (string) ($attrs['className'] ?? ''));
return $this->htmlAttrs(array(
'id' => (string) ($attrs['anchor'] ?? ''),
'class' => $classes,
'style' => $support['style'],
));
}
/**
* Serialize the canonical block `style` OBJECT into the has-* support classes
* and inline CSS string WordPress emits in `save()`. A legacy raw `style`
* string is passed through unchanged for backward compatibility.
*
* @param mixed $style
* @return array{classes: string, style: string}
*/
private function styleSupport(mixed $style): array
{
if ( is_array($style) ) {
return $this->styleMapper()->serialize($style);
}
return array(
'classes' => '',
'style' => is_string($style) ? $style : '',
);
}
/**
* @param array<string, mixed> $attrs
*/
private function presetColorClasses(array $attrs): string
{
$classes = array();
$textColor = $this->safeSlug((string) ($attrs['textColor'] ?? ''));
if ( '' !== $textColor ) {
$classes[] = 'has-' . $textColor . '-color';
$classes[] = 'has-text-color';
}
$backgroundColor = $this->safeSlug((string) ($attrs['backgroundColor'] ?? ''));
if ( '' !== $backgroundColor ) {
$classes[] = 'has-' . $backgroundColor . '-background-color';
$classes[] = 'has-background';
}
return implode(' ', $classes);
}
private function layoutClasses(mixed $layout, string $baseClass): string
{
if ( ! is_array($layout) ) {
return '';
}
$type = $this->safeSlug((string) ($layout['type'] ?? ''));
if ( ! in_array($type, array( 'constrained', 'flex', 'flow', 'grid' ), true) ) {
return '';
}
return $this->mergeClassNames(
'is-layout-' . $type,
'' !== $baseClass ? $baseClass . '-is-layout-' . $type : ''
);
}
private function safeSlug(string $value): string
{
$value = strtolower(trim($value));
return preg_match('/^[a-z0-9_-]+$/', $value) ? $value : '';
}
/**
* @param array<string, string> $attrs
* @param array<int, string> $includeEmpty
*/
private function htmlAttrs(array $attrs, array $includeEmpty = array()): string
{
$html = '';
foreach ( $attrs as $name => $value ) {
if ( '' === $value && ! in_array($name, $includeEmpty, true) ) {
continue;
}
$html .= ' ' . $name . '="' . htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '"';
}
return $html;
}
}