[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp-theme-json.php (source)

   1  <?php
   2  /**
   3   * WP_Theme_JSON class
   4   *
   5   * @package WordPress
   6   * @subpackage Theme
   7   * @since 5.8.0
   8   */
   9  
  10  /**
  11   * Class that encapsulates the processing of structures that adhere to the theme.json spec.
  12   *
  13   * This class is for internal core usage and is not supposed to be used by extenders (plugins and/or themes).
  14   * This is a low-level API that may need to do breaking changes. Please,
  15   * use get_global_settings, get_global_styles, and get_global_stylesheet instead.
  16   *
  17   * @access private
  18   */
  19  #[AllowDynamicProperties]
  20  class WP_Theme_JSON {
  21  
  22      /**
  23       * Container of data in theme.json format.
  24       *
  25       * @since 5.8.0
  26       * @var array
  27       */
  28      protected $theme_json = null;
  29  
  30      /**
  31       * Holds block metadata extracted from block.json
  32       * to be shared among all instances so we don't
  33       * process it twice.
  34       *
  35       * @since 5.8.0
  36       * @since 6.1.0 Initialize as an empty array.
  37       * @var array
  38       */
  39      protected static $blocks_metadata = array();
  40  
  41      /**
  42       * The CSS selector for the top-level preset settings.
  43       *
  44       * @since 6.6.0
  45       * @var string
  46       */
  47      const ROOT_CSS_PROPERTIES_SELECTOR = ':root';
  48  
  49      /**
  50       * The CSS selector for the top-level styles.
  51       *
  52       * @since 5.8.0
  53       * @var string
  54       */
  55      const ROOT_BLOCK_SELECTOR = 'body';
  56  
  57      /**
  58       * The sources of data this object can represent.
  59       *
  60       * @since 5.8.0
  61       * @since 6.1.0 Added 'blocks'.
  62       * @var string[]
  63       */
  64      const VALID_ORIGINS = array(
  65          'default',
  66          'blocks',
  67          'theme',
  68          'custom',
  69      );
  70  
  71      /**
  72       * Presets are a set of values that serve
  73       * to bootstrap some styles: colors, font sizes, etc.
  74       *
  75       * They are a unkeyed array of values such as:
  76       *
  77       *     array(
  78       *       array(
  79       *         'slug'      => 'unique-name-within-the-set',
  80       *         'name'      => 'Name for the UI',
  81       *         <value_key> => 'value'
  82       *       ),
  83       *     )
  84       *
  85       * This contains the necessary metadata to process them:
  86       *
  87       * - path             => Where to find the preset within the settings section.
  88       * - prevent_override => Disables override of default presets by theme presets.
  89       *                       The relationship between whether to override the defaults
  90       *                       and whether the defaults are enabled is inverse:
  91       *                         - If defaults are enabled  => theme presets should not be overridden
  92       *                         - If defaults are disabled => theme presets should be overridden
  93       *                       For example, a theme sets defaultPalette to false,
  94       *                       making the default palette hidden from the user.
  95       *                       In that case, we want all the theme presets to be present,
  96       *                       so they should override the defaults by setting this false.
  97       * - use_default_names => whether to use the default names
  98       * - value_key        => the key that represents the value
  99       * - value_func       => optionally, instead of value_key, a function to generate
 100       *                       the value that takes a preset as an argument
 101       *                       (either value_key or value_func should be present)
 102       * - css_vars         => template string to use in generating the CSS Custom Property.
 103       *                       Example output: "--wp--preset--duotone--blue: <value>" will generate as many CSS Custom Properties as presets defined
 104       *                       substituting the $slug for the slug's value for each preset value.
 105       * - classes          => array containing a structure with the classes to
 106       *                       generate for the presets, where for each array item
 107       *                       the key is the class name and the value the property name.
 108       *                       The "$slug" substring will be replaced by the slug of each preset.
 109       *                       For example:
 110       *                       'classes' => array(
 111       *                         '.has-$slug-color'            => 'color',
 112       *                         '.has-$slug-background-color' => 'background-color',
 113       *                         '.has-$slug-border-color'     => 'border-color',
 114       *                       )
 115       * - properties       => array of CSS properties to be used by kses to
 116       *                       validate the content of each preset
 117       *                       by means of the remove_insecure_properties method.
 118       *
 119       * @since 5.8.0
 120       * @since 5.9.0 Added the `color.duotone` and `typography.fontFamilies` presets,
 121       *              `use_default_names` preset key, and simplified the metadata structure.
 122       * @since 6.0.0 Replaced `override` with `prevent_override` and updated the
 123       *              `prevent_override` value for `color.duotone` to use `color.defaultDuotone`.
 124       * @since 6.2.0 Added 'shadow' presets.
 125       * @since 6.3.0 Replaced value_func for duotone with `null`. Custom properties are handled by class-wp-duotone.php.
 126       * @since 6.6.0 Added the `dimensions.aspectRatios` and `dimensions.defaultAspectRatios` presets.
 127       *              Updated the 'prevent_override' value for font size presets to use 'typography.defaultFontSizes'
 128       *              and spacing size presets to use `spacing.defaultSpacingSizes`.
 129       * @since 6.9.0 Added `border.radiusSizes`.
 130       * @var array
 131       */
 132      const PRESETS_METADATA = array(
 133          array(
 134              'path'              => array( 'dimensions', 'aspectRatios' ),
 135              'prevent_override'  => array( 'dimensions', 'defaultAspectRatios' ),
 136              'use_default_names' => false,
 137              'value_key'         => 'ratio',
 138              'css_vars'          => '--wp--preset--aspect-ratio--$slug',
 139              'classes'           => array(),
 140              'properties'        => array( 'aspect-ratio' ),
 141          ),
 142          array(
 143              'path'              => array( 'color', 'palette' ),
 144              'prevent_override'  => array( 'color', 'defaultPalette' ),
 145              'use_default_names' => false,
 146              'value_key'         => 'color',
 147              'css_vars'          => '--wp--preset--color--$slug',
 148              'classes'           => array(
 149                  '.has-$slug-color'            => 'color',
 150                  '.has-$slug-background-color' => 'background-color',
 151                  '.has-$slug-border-color'     => 'border-color',
 152              ),
 153              'properties'        => array( 'color', 'background-color', 'border-color' ),
 154          ),
 155          array(
 156              'path'              => array( 'color', 'gradients' ),
 157              'prevent_override'  => array( 'color', 'defaultGradients' ),
 158              'use_default_names' => false,
 159              'value_key'         => 'gradient',
 160              'css_vars'          => '--wp--preset--gradient--$slug',
 161              'classes'           => array( '.has-$slug-gradient-background' => 'background' ),
 162              'properties'        => array( 'background' ),
 163          ),
 164          array(
 165              'path'              => array( 'color', 'duotone' ),
 166              'prevent_override'  => array( 'color', 'defaultDuotone' ),
 167              'use_default_names' => false,
 168              'value_func'        => null, // CSS Custom Properties for duotone are handled by block supports in class-wp-duotone.php.
 169              'css_vars'          => null,
 170              'classes'           => array(),
 171              'properties'        => array( 'filter' ),
 172          ),
 173          array(
 174              'path'              => array( 'typography', 'fontSizes' ),
 175              'prevent_override'  => array( 'typography', 'defaultFontSizes' ),
 176              'use_default_names' => true,
 177              'value_func'        => 'wp_get_typography_font_size_value',
 178              'css_vars'          => '--wp--preset--font-size--$slug',
 179              'classes'           => array( '.has-$slug-font-size' => 'font-size' ),
 180              'properties'        => array( 'font-size' ),
 181          ),
 182          array(
 183              'path'              => array( 'typography', 'fontFamilies' ),
 184              'prevent_override'  => false,
 185              'use_default_names' => false,
 186              'value_key'         => 'fontFamily',
 187              'css_vars'          => '--wp--preset--font-family--$slug',
 188              'classes'           => array( '.has-$slug-font-family' => 'font-family' ),
 189              'properties'        => array( 'font-family' ),
 190          ),
 191          array(
 192              'path'              => array( 'spacing', 'spacingSizes' ),
 193              'prevent_override'  => array( 'spacing', 'defaultSpacingSizes' ),
 194              'use_default_names' => true,
 195              'value_key'         => 'size',
 196              'css_vars'          => '--wp--preset--spacing--$slug',
 197              'classes'           => array(),
 198              'properties'        => array( 'padding', 'margin' ),
 199          ),
 200          array(
 201              'path'              => array( 'shadow', 'presets' ),
 202              'prevent_override'  => array( 'shadow', 'defaultPresets' ),
 203              'use_default_names' => false,
 204              'value_key'         => 'shadow',
 205              'css_vars'          => '--wp--preset--shadow--$slug',
 206              'classes'           => array(),
 207              'properties'        => array( 'box-shadow' ),
 208          ),
 209          array(
 210              'path'              => array( 'border', 'radiusSizes' ),
 211              'prevent_override'  => false,
 212              'use_default_names' => false,
 213              'value_key'         => 'size',
 214              'css_vars'          => '--wp--preset--border-radius--$slug',
 215              'classes'           => array(),
 216              'properties'        => array( 'border-radius' ),
 217          ),
 218          array(
 219              'path'              => array( 'dimensions', 'dimensionSizes' ),
 220              'prevent_override'  => false,
 221              'use_default_names' => false,
 222              'value_key'         => 'size',
 223              'css_vars'          => '--wp--preset--dimension--$slug',
 224              'classes'           => array(),
 225              'properties'        => array( 'width', 'height', 'min-height' ),
 226          ),
 227      );
 228  
 229      /**
 230       * Metadata for style properties.
 231       *
 232       * Each element is a direct mapping from the CSS property name to the
 233       * path to the value in theme.json & block attributes.
 234       *
 235       * @since 5.8.0
 236       * @since 5.9.0 Added the `border-*`, `font-family`, `font-style`, `font-weight`,
 237       *              `letter-spacing`, `margin-*`, `padding-*`, `--wp--style--block-gap`,
 238       *              `text-decoration`, `text-transform`, and `filter` properties,
 239       *              simplified the metadata structure.
 240       * @since 6.1.0 Added the `border-*-color`, `border-*-width`, `border-*-style`,
 241       *              `--wp--style--root--padding-*`, and `box-shadow` properties,
 242       *              removed the `--wp--style--block-gap` property.
 243       * @since 6.2.0 Added `outline-*`, and `min-height` properties.
 244       * @since 6.3.0 Added `column-count` property.
 245       * @since 6.4.0 Added `writing-mode` property.
 246       * @since 6.5.0 Added `aspect-ratio` property.
 247       * @since 6.6.0 Added `background-[image|position|repeat|size]` properties.
 248       * @since 6.7.0 Added `background-attachment` property.
 249       * @since 7.0.0 Added `dimensions.width` and `dimensions.height`.
 250       *              Added `text-indent` property.
 251       * @since 7.1.0 Added `min-width` and `text-shadow`.
 252       * @var array
 253       */
 254      const PROPERTIES_METADATA = array(
 255          'aspect-ratio'                      => array( 'dimensions', 'aspectRatio' ),
 256          'background'                        => array( 'color', 'gradient' ),
 257          'background-color'                  => array( 'color', 'background' ),
 258          'background-image'                  => array( 'background', 'backgroundImage' ),
 259          'background-position'               => array( 'background', 'backgroundPosition' ),
 260          'background-repeat'                 => array( 'background', 'backgroundRepeat' ),
 261          'background-size'                   => array( 'background', 'backgroundSize' ),
 262          'background-attachment'             => array( 'background', 'backgroundAttachment' ),
 263          'border-radius'                     => array( 'border', 'radius' ),
 264          'border-top-left-radius'            => array( 'border', 'radius', 'topLeft' ),
 265          'border-top-right-radius'           => array( 'border', 'radius', 'topRight' ),
 266          'border-bottom-left-radius'         => array( 'border', 'radius', 'bottomLeft' ),
 267          'border-bottom-right-radius'        => array( 'border', 'radius', 'bottomRight' ),
 268          'border-color'                      => array( 'border', 'color' ),
 269          'border-width'                      => array( 'border', 'width' ),
 270          'border-style'                      => array( 'border', 'style' ),
 271          'border-top-color'                  => array( 'border', 'top', 'color' ),
 272          'border-top-width'                  => array( 'border', 'top', 'width' ),
 273          'border-top-style'                  => array( 'border', 'top', 'style' ),
 274          'border-right-color'                => array( 'border', 'right', 'color' ),
 275          'border-right-width'                => array( 'border', 'right', 'width' ),
 276          'border-right-style'                => array( 'border', 'right', 'style' ),
 277          'border-bottom-color'               => array( 'border', 'bottom', 'color' ),
 278          'border-bottom-width'               => array( 'border', 'bottom', 'width' ),
 279          'border-bottom-style'               => array( 'border', 'bottom', 'style' ),
 280          'border-left-color'                 => array( 'border', 'left', 'color' ),
 281          'border-left-width'                 => array( 'border', 'left', 'width' ),
 282          'border-left-style'                 => array( 'border', 'left', 'style' ),
 283          'color'                             => array( 'color', 'text' ),
 284          'text-align'                        => array( 'typography', 'textAlign' ),
 285          'column-count'                      => array( 'typography', 'textColumns' ),
 286          'font-family'                       => array( 'typography', 'fontFamily' ),
 287          'font-size'                         => array( 'typography', 'fontSize' ),
 288          'font-style'                        => array( 'typography', 'fontStyle' ),
 289          'font-weight'                       => array( 'typography', 'fontWeight' ),
 290          'letter-spacing'                    => array( 'typography', 'letterSpacing' ),
 291          'line-height'                       => array( 'typography', 'lineHeight' ),
 292          'margin'                            => array( 'spacing', 'margin' ),
 293          'margin-top'                        => array( 'spacing', 'margin', 'top' ),
 294          'margin-right'                      => array( 'spacing', 'margin', 'right' ),
 295          'margin-bottom'                     => array( 'spacing', 'margin', 'bottom' ),
 296          'margin-left'                       => array( 'spacing', 'margin', 'left' ),
 297          'min-height'                        => array( 'dimensions', 'minHeight' ),
 298          'min-width'                         => array( 'dimensions', 'minWidth' ),
 299          'outline-color'                     => array( 'outline', 'color' ),
 300          'outline-offset'                    => array( 'outline', 'offset' ),
 301          'outline-style'                     => array( 'outline', 'style' ),
 302          'outline-width'                     => array( 'outline', 'width' ),
 303          'padding'                           => array( 'spacing', 'padding' ),
 304          'padding-top'                       => array( 'spacing', 'padding', 'top' ),
 305          'padding-right'                     => array( 'spacing', 'padding', 'right' ),
 306          'padding-bottom'                    => array( 'spacing', 'padding', 'bottom' ),
 307          'padding-left'                      => array( 'spacing', 'padding', 'left' ),
 308          '--wp--style--root--padding'        => array( 'spacing', 'padding' ),
 309          '--wp--style--root--padding-top'    => array( 'spacing', 'padding', 'top' ),
 310          '--wp--style--root--padding-right'  => array( 'spacing', 'padding', 'right' ),
 311          '--wp--style--root--padding-bottom' => array( 'spacing', 'padding', 'bottom' ),
 312          '--wp--style--root--padding-left'   => array( 'spacing', 'padding', 'left' ),
 313          'text-decoration'                   => array( 'typography', 'textDecoration' ),
 314          'text-shadow'                       => array( 'typography', 'textShadow' ),
 315          'text-transform'                    => array( 'typography', 'textTransform' ),
 316          'text-indent'                       => array( 'typography', 'textIndent' ),
 317          'filter'                            => array( 'filter', 'duotone' ),
 318          'box-shadow'                        => array( 'shadow' ),
 319          'height'                            => array( 'dimensions', 'height' ),
 320          'width'                             => array( 'dimensions', 'width' ),
 321          'writing-mode'                      => array( 'typography', 'writingMode' ),
 322      );
 323  
 324      /**
 325       * Indirect metadata for style properties that are not directly output.
 326       *
 327       * Each element maps from a CSS property name to an array of
 328       * paths to the value in theme.json & block attributes.
 329       *
 330       * Indirect properties are not output directly by `compute_style_properties`,
 331       * but are used elsewhere in the processing of global styles. The indirect
 332       * property is used to validate whether a style value is allowed.
 333       *
 334       * @since 6.2.0
 335       * @since 6.6.0 Added background-image properties.
 336       * @since 7.1.0 Added `background.gradient` to `background-image` paths.
 337       * @var array
 338       */
 339      const INDIRECT_PROPERTIES_METADATA = array(
 340          'gap'              => array(
 341              array( 'spacing', 'blockGap' ),
 342          ),
 343          'column-gap'       => array(
 344              array( 'spacing', 'blockGap', 'left' ),
 345          ),
 346          'row-gap'          => array(
 347              array( 'spacing', 'blockGap', 'top' ),
 348          ),
 349          'max-width'        => array(
 350              array( 'layout', 'contentSize' ),
 351              array( 'layout', 'wideSize' ),
 352          ),
 353          'background-image' => array(
 354              array( 'background', 'backgroundImage', 'url' ),
 355              array( 'background', 'gradient' ),
 356          ),
 357      );
 358  
 359      /**
 360       * Protected style properties.
 361       *
 362       * These style properties are only rendered if a setting enables it
 363       * via a value other than `null`.
 364       *
 365       * Each element maps the style property to the corresponding theme.json
 366       * setting key.
 367       *
 368       * @since 5.9.0
 369       * @var array
 370       */
 371      const PROTECTED_PROPERTIES = array(
 372          'spacing.blockGap' => array( 'spacing', 'blockGap' ),
 373      );
 374  
 375      /**
 376       * The top-level keys a theme.json can have.
 377       *
 378       * @since 5.8.0 As `ALLOWED_TOP_LEVEL_KEYS`.
 379       * @since 5.9.0 Renamed from `ALLOWED_TOP_LEVEL_KEYS` to `VALID_TOP_LEVEL_KEYS`,
 380       *              added the `customTemplates` and `templateParts` values.
 381       * @since 6.3.0 Added the `description` value.
 382       * @since 6.6.0 Added `blockTypes` to support block style variation theme.json partials.
 383       * @var string[]
 384       */
 385      const VALID_TOP_LEVEL_KEYS = array(
 386          'blockTypes',
 387          'customTemplates',
 388          'description',
 389          'patterns',
 390          'settings',
 391          'slug',
 392          'styles',
 393          'templateParts',
 394          'title',
 395          'version',
 396      );
 397  
 398      /**
 399       * The valid properties under the settings key.
 400       *
 401       * @since 5.8.0 As `ALLOWED_SETTINGS`.
 402       * @since 5.9.0 Renamed from `ALLOWED_SETTINGS` to `VALID_SETTINGS`,
 403       *              added new properties for `border`, `color`, `spacing`,
 404       *              and `typography`, and renamed others according to the new schema.
 405       * @since 6.0.0 Added `color.defaultDuotone`.
 406       * @since 6.1.0 Added `layout.definitions` and `useRootPaddingAwareAlignments`.
 407       * @since 6.2.0 Added `dimensions.minHeight`, 'shadow.presets', 'shadow.defaultPresets',
 408       *              `position.fixed` and `position.sticky`.
 409       * @since 6.3.0 Added support for `typography.textColumns`, removed `layout.definitions`.
 410       * @since 6.4.0 Added support for `layout.allowEditing`, `background.backgroundImage`,
 411       *              `typography.writingMode`, `lightbox.enabled` and `lightbox.allowEditing`.
 412       * @since 6.5.0 Added support for `layout.allowCustomContentAndWideSize`,
 413       *              `background.backgroundSize` and `dimensions.aspectRatio`.
 414       * @since 6.6.0 Added support for 'dimensions.aspectRatios', 'dimensions.defaultAspectRatios',
 415       *              'typography.defaultFontSizes', and 'spacing.defaultSpacingSizes'.
 416       * @since 6.9.0 Added support for `border.radiusSizes`.
 417       * @since 7.0.0 Added type markers to the schema for boolean values.
 418       *              Added support for `dimensions.width` and `dimensions.height`.
 419       *              Added support for `typography.textIndent`.
 420       * @since 7.1.0 Added `viewport` property.
 421       *              Added support for `background.gradient`, `dimensions.minWidth` and `blockVisibility.allowEditing`.
 422       * @var array
 423       */
 424      const VALID_SETTINGS = array(
 425          'appearanceTools'               => null,
 426          'useRootPaddingAwareAlignments' => null,
 427          'background'                    => array(
 428              'backgroundImage' => null,
 429              'backgroundSize'  => null,
 430              'gradient'        => null,
 431          ),
 432          'border'                        => array(
 433              'color'       => null,
 434              'radius'      => null,
 435              'radiusSizes' => null,
 436              'style'       => null,
 437              'width'       => null,
 438          ),
 439          'color'                         => array(
 440              'background'       => null,
 441              'custom'           => null,
 442              'customDuotone'    => null,
 443              'customGradient'   => null,
 444              'defaultDuotone'   => null,
 445              'defaultGradients' => null,
 446              'defaultPalette'   => null,
 447              'duotone'          => null,
 448              'gradients'        => null,
 449              'link'             => null,
 450              'heading'          => null,
 451              'button'           => null,
 452              'caption'          => null,
 453              'palette'          => null,
 454              'text'             => null,
 455          ),
 456          'custom'                        => null,
 457          'dimensions'                    => array(
 458              'aspectRatio'         => null,
 459              'aspectRatios'        => null,
 460              'defaultAspectRatios' => null,
 461              'dimensionSizes'      => null,
 462              'height'              => null,
 463              'minHeight'           => null,
 464              'minWidth'            => null,
 465              'width'               => null,
 466          ),
 467          'layout'                        => array(
 468              'contentSize'                   => null,
 469              'wideSize'                      => null,
 470              'allowEditing'                  => null,
 471              'allowCustomContentAndWideSize' => null,
 472          ),
 473          'lightbox'                      => array(
 474              'enabled'      => true,
 475              'allowEditing' => true,
 476          ),
 477          'position'                      => array(
 478              'fixed'  => null,
 479              'sticky' => null,
 480          ),
 481          'blockVisibility'               => array(
 482              'allowEditing' => true,
 483          ),
 484          'spacing'                       => array(
 485              'customSpacingSize'   => null,
 486              'defaultSpacingSizes' => null,
 487              'spacingSizes'        => null,
 488              'spacingScale'        => null,
 489              'blockGap'            => null,
 490              'margin'              => null,
 491              'padding'             => null,
 492              'units'               => null,
 493          ),
 494          'shadow'                        => array(
 495              'presets'        => null,
 496              'defaultPresets' => null,
 497          ),
 498          'typography'                    => array(
 499              'fluid'            => null,
 500              'customFontSize'   => null,
 501              'defaultFontSizes' => null,
 502              'dropCap'          => null,
 503              'fontFamilies'     => null,
 504              'fontSizes'        => null,
 505              'fontStyle'        => null,
 506              'fontWeight'       => null,
 507              'letterSpacing'    => null,
 508              'lineHeight'       => null,
 509              'textAlign'        => null,
 510              'textColumns'      => null,
 511              'textDecoration'   => null,
 512              'textIndent'       => null,
 513              'textTransform'    => null,
 514              'writingMode'      => null,
 515          ),
 516          'viewport'                      => array(
 517              'mobile' => null,
 518              'tablet' => null,
 519          ),
 520      );
 521  
 522      /**
 523       * The valid properties for fontFamilies under settings key.
 524       *
 525       * @since 6.5.0
 526       * @var array
 527       */
 528      const FONT_FAMILY_SCHEMA = array(
 529          array(
 530              'fontFamily' => null,
 531              'name'       => null,
 532              'slug'       => null,
 533              'fontFace'   => array(
 534                  array(
 535                      'ascentOverride'        => null,
 536                      'descentOverride'       => null,
 537                      'fontDisplay'           => null,
 538                      'fontFamily'            => null,
 539                      'fontFeatureSettings'   => null,
 540                      'fontStyle'             => null,
 541                      'fontStretch'           => null,
 542                      'fontVariationSettings' => null,
 543                      'fontWeight'            => null,
 544                      'lineGapOverride'       => null,
 545                      'sizeAdjust'            => null,
 546                      'src'                   => null,
 547                      'unicodeRange'          => null,
 548                  ),
 549              ),
 550          ),
 551      );
 552  
 553      /**
 554       * The valid properties under the styles key.
 555       *
 556       * @since 5.8.0 As `ALLOWED_STYLES`.
 557       * @since 5.9.0 Renamed from `ALLOWED_STYLES` to `VALID_STYLES`,
 558       *              added new properties for `border`, `filter`, `spacing`,
 559       *              and `typography`.
 560       * @since 6.1.0 Added new side properties for `border`,
 561       *              added new property `shadow`,
 562       *              updated `blockGap` to be allowed at any level.
 563       * @since 6.2.0 Added `outline`, and `minHeight` properties.
 564       * @since 6.3.0 Added support for `typography.textColumns`.
 565       * @since 6.5.0 Added support for `dimensions.aspectRatio`.
 566       * @since 6.6.0 Added `background` sub properties to top-level only.
 567       * @since 7.0.0 Added support for `dimensions.width` and `dimensions.height`.
 568       * @since 7.1.0 Added support for `background.gradient`,`dimensions.minWidth`,
 569       *              and `typography.textShadow`.
 570       * @var array
 571       */
 572      const VALID_STYLES = array(
 573          'background' => array(
 574              'backgroundImage'      => null,
 575              'backgroundPosition'   => null,
 576              'backgroundRepeat'     => null,
 577              'backgroundSize'       => null,
 578              'backgroundAttachment' => null,
 579              'gradient'             => null,
 580          ),
 581          'border'     => array(
 582              'color'  => null,
 583              'radius' => null,
 584              'style'  => null,
 585              'width'  => null,
 586              'top'    => null,
 587              'right'  => null,
 588              'bottom' => null,
 589              'left'   => null,
 590          ),
 591          'color'      => array(
 592              'background' => null,
 593              'gradient'   => null,
 594              'text'       => null,
 595          ),
 596          'dimensions' => array(
 597              'aspectRatio' => null,
 598              'height'      => null,
 599              'minHeight'   => null,
 600              'minWidth'    => null,
 601              'width'       => null,
 602          ),
 603          'filter'     => array(
 604              'duotone' => null,
 605          ),
 606          'outline'    => array(
 607              'color'  => null,
 608              'offset' => null,
 609              'style'  => null,
 610              'width'  => null,
 611          ),
 612          'shadow'     => null,
 613          'spacing'    => array(
 614              'margin'   => null,
 615              'padding'  => null,
 616              'blockGap' => null,
 617          ),
 618          'typography' => array(
 619              'fontFamily'     => null,
 620              'fontSize'       => null,
 621              'fontStyle'      => null,
 622              'fontWeight'     => null,
 623              'letterSpacing'  => null,
 624              'lineHeight'     => null,
 625              'textAlign'      => null,
 626              'textColumns'    => null,
 627              'textDecoration' => null,
 628              'textIndent'     => null,
 629              'textShadow'     => null,
 630              'textTransform'  => null,
 631              'writingMode'    => null,
 632          ),
 633          'css'        => null,
 634      );
 635  
 636      /**
 637       * Defines which pseudo selectors are enabled for which elements.
 638       *
 639       * The order of the selectors should be: link, any-link, visited, hover, focus, focus-visible, active.
 640       * This is to ensure the user action (hover, focus and active) styles have a higher
 641       * specificity than the visited styles, which in turn have a higher specificity than
 642       * the unvisited styles.
 643       *
 644       * See https://core.trac.wordpress.org/ticket/56928.
 645       * Note: this will affect both top-level and block-level elements.
 646       *
 647       * @since 6.1.0
 648       * @since 6.2.0 Added support for ':link' and ':any-link'.
 649       * @since 6.8.0 Added support for ':focus-visible'.
 650       * @since 6.9.0 Added `textInput` and `select` elements.
 651       * @var array
 652       */
 653      const VALID_ELEMENT_PSEUDO_SELECTORS = array(
 654          'link'   => array( ':link', ':any-link', ':visited', ':hover', ':focus', ':focus-visible', ':active' ),
 655          'button' => array( ':link', ':any-link', ':visited', ':hover', ':focus', ':focus-visible', ':active' ),
 656      );
 657  
 658      /**
 659       * The valid pseudo-selectors that can be used for blocks.
 660       *
 661       * @since 7.0
 662       * @var array
 663       */
 664      const VALID_BLOCK_PSEUDO_SELECTORS = array(
 665          'core/button'          => array( ':hover', ':focus', ':focus-visible', ':active' ),
 666          'core/navigation-link' => array( ':hover', ':focus', ':focus-visible', ':active' ),
 667      );
 668  
 669      /**
 670       * Custom states for blocks that map to CSS class selectors rather than
 671       * CSS pseudo-selectors. Values use the '-' prefix (e.g. '-current') to
 672       * distinguish them from real CSS pseudo-selectors and breakpoint states.
 673       *
 674       * The CSS selector for each state is defined in the block's block.json
 675       * under `selectors.states`, e.g.:
 676       *
 677       *   "selectors": { "states": { "-current": ".some-css-selector" } }
 678       *
 679       * This constant controls which states are valid in theme.json for a given
 680       * block. Blocks listed here also inherit their VALID_BLOCK_PSEUDO_SELECTORS
 681       * as valid sub-states, producing compound selectors such as
 682       * `.wp-block-navigation-item.current-menu-item:hover`.
 683       *
 684       * @since 7.1.0
 685       * @var array
 686       */
 687      const VALID_BLOCK_CUSTOM_STATES = array(
 688          'core/navigation-link' => array( '-current' ),
 689      );
 690  
 691      /**
 692       * Default viewport breakpoint sizes.
 693       *
 694       * @since 7.1.0
 695       * @var array
 696       */
 697      const DEFAULT_VIEWPORT_BREAKPOINTS = array(
 698          'mobile' => '480px',
 699          'tablet' => '782px',
 700      );
 701  
 702      /**
 703       * Returns CSS media queries for responsive viewport style states.
 704       *
 705       * Breakpoint values are read from `settings.viewport`, sanitized, and
 706       * normalized before the media query strings are generated. By default, the
 707       * returned keys are the theme.json style-state names (`@mobile`, `@tablet`).
 708       * When `$options['include_desktop']` is truthy, `@desktop` is included.
 709       *
 710       * @since 7.1.0
 711       *
 712       * @param mixed $viewport_settings Viewport settings from theme.json.
 713       * @param array $options           {
 714       *     Optional. Options for generating media queries.
 715       *
 716       *     @type bool $include_desktop Whether to include the desktop media query. Default false.
 717       * }
 718       * @return array Responsive media queries.
 719       */
 720  	public static function get_viewport_media_queries( $viewport_settings = null, $options = array() ) {
 721          $breakpoints = static::sanitize_viewport_settings( $viewport_settings );
 722  
 723          $responsive_media_queries = array();
 724  
 725          if ( isset( $breakpoints['mobile'] ) ) {
 726              $responsive_media_queries['@mobile'] = "@media (width <= {$breakpoints['mobile']})";
 727          }
 728  
 729          if ( isset( $breakpoints['tablet'] ) ) {
 730              $responsive_media_queries['@tablet'] = isset( $breakpoints['mobile'] )
 731                  ? sprintf(
 732                      '@media (%s < width <= %s)',
 733                      $breakpoints['mobile'],
 734                      $breakpoints['tablet']
 735                  )
 736                  : "@media (width <= {$breakpoints['tablet']})";
 737          }
 738  
 739          if ( ! empty( $options['include_desktop'] ) ) {
 740              if ( isset( $breakpoints['tablet'] ) ) {
 741                  $desktop_breakpoint = $breakpoints['tablet'];
 742              } else {
 743                  $desktop_breakpoint = $breakpoints['mobile'];
 744              }
 745  
 746              $responsive_media_queries['@desktop'] =
 747                  "@media (width > {$desktop_breakpoint})";
 748          }
 749  
 750          return $responsive_media_queries;
 751      }
 752  
 753      /**
 754       * Checks whether a viewport breakpoint value is a safe CSS length.
 755       *
 756       * Viewport breakpoints are limited to numeric `px`, `em`, and `rem` lengths.
 757       * CSS functions, percentages, and other units are rejected because breakpoint
 758       * values are interpolated into generated media queries.
 759       *
 760       * @since 7.1.0
 761       *
 762       * @param mixed $value Value to check.
 763       * @return bool Whether the value is valid.
 764       */
 765  	private static function is_valid_viewport_breakpoint_size( $value ) {
 766          if ( ! is_string( $value ) ) {
 767              return false;
 768          }
 769  
 770          $value = trim( $value );
 771          if ( '' === $value ) {
 772              return false;
 773          }
 774  
 775          return 1 === preg_match( '/^(?:\d+|\d*\.\d+)(?:px|em|rem)$/', $value );
 776      }
 777  
 778      /**
 779       * Converts a valid viewport breakpoint size to pixels for ordering checks.
 780       *
 781       * Generated media queries keep the original units. This method only
 782       * normalizes values so `mobile` and `tablet` can be compared safely. `em`
 783       * and `rem` lengths use a 16px base for comparison.
 784       *
 785       * @since 7.1.0
 786       *
 787       * @param mixed $value Viewport breakpoint size.
 788       * @return float|null Viewport breakpoint size in pixels, or null when invalid.
 789       */
 790  	private static function get_viewport_breakpoint_value_in_pixels( $value ) {
 791          if ( ! static::is_valid_viewport_breakpoint_size( $value ) ) {
 792              return null;
 793          }
 794  
 795          $value = trim( $value );
 796          $unit  = substr( $value, -3 );
 797          if ( 'rem' === $unit ) {
 798              $number = (float) substr( $value, 0, -3 );
 799          } else {
 800              $unit   = substr( $value, -2 );
 801              $number = (float) substr( $value, 0, -2 );
 802          }
 803  
 804          /*
 805           * Use the most common browser default font size as the base for em/rem
 806           * media query conversions. This pixel value is only used to compare
 807           * breakpoint order; generated media queries keep the original units.
 808           */
 809          return 'px' === $unit ? $number : $number * 16;
 810      }
 811  
 812      /**
 813       * Sanitizes and normalizes viewport breakpoint settings.
 814       *
 815       * Keeps only supported breakpoint keys, trims valid CSS lengths, and returns
 816       * the default breakpoints when no valid custom breakpoint is provided. When
 817       * only one breakpoint is valid, it remains keyed by its configured state and
 818       * uses a single max-width media query. When `tablet` is not larger than
 819       * `mobile`, it is removed.
 820       *
 821       * @since 7.1.0
 822       *
 823       * @param mixed $viewport_settings Viewport settings from theme.json.
 824       * @return array Sanitized viewport breakpoint settings.
 825       */
 826  	private static function sanitize_viewport_settings( $viewport_settings ) {
 827          if ( ! is_array( $viewport_settings ) ) {
 828              return static::DEFAULT_VIEWPORT_BREAKPOINTS;
 829          }
 830  
 831          $breakpoints = array();
 832          foreach ( array_keys( static::DEFAULT_VIEWPORT_BREAKPOINTS ) as $breakpoint ) {
 833              $value = $viewport_settings[ $breakpoint ] ?? null;
 834              $px    = static::get_viewport_breakpoint_value_in_pixels( $value );
 835              if ( null !== $px ) {
 836                  $breakpoints[ $breakpoint ] = array(
 837                      'value' => trim( $value ),
 838                      'px'    => $px,
 839                  );
 840              }
 841          }
 842  
 843          if ( empty( $breakpoints ) ) {
 844              return static::DEFAULT_VIEWPORT_BREAKPOINTS;
 845          }
 846  
 847          if ( 1 === count( $breakpoints ) ) {
 848              $breakpoint = key( $breakpoints );
 849              return array( $breakpoint => $breakpoints[ $breakpoint ]['value'] );
 850          }
 851  
 852          $sanitized = array( 'mobile' => $breakpoints['mobile']['value'] );
 853  
 854          if ( isset( $breakpoints['tablet'] ) && $breakpoints['mobile']['px'] < $breakpoints['tablet']['px'] ) {
 855              $sanitized['tablet'] = $breakpoints['tablet']['value'];
 856          }
 857  
 858          return $sanitized;
 859      }
 860  
 861      /**
 862       * The valid elements that can be found under styles.
 863       *
 864       * @since 5.8.0
 865       * @since 6.1.0 Added `heading`, `button`, and `caption` elements.
 866       * @var string[]
 867       */
 868      const ELEMENTS = array(
 869          'link'      => 'a:where(:not(.wp-element-button))', // The `where` is needed to lower the specificity.
 870          'heading'   => 'h1, h2, h3, h4, h5, h6',
 871          'h1'        => 'h1',
 872          'h2'        => 'h2',
 873          'h3'        => 'h3',
 874          'h4'        => 'h4',
 875          'h5'        => 'h5',
 876          'h6'        => 'h6',
 877          // We have the .wp-block-button__link class so that this will target older buttons that have been serialized.
 878          'button'    => '.wp-element-button, .wp-block-button__link',
 879          // The block classes are necessary to target older content that won't use the new class names.
 880          'caption'   => '.wp-element-caption, .wp-block-audio figcaption, .wp-block-embed figcaption, .wp-block-gallery figcaption, .wp-block-image figcaption, .wp-block-table figcaption, .wp-block-video figcaption',
 881          'cite'      => 'cite',
 882          'textInput' => 'textarea, input:where([type=email],[type=number],[type=password],[type=search],[type=text],[type=tel],[type=url])',
 883          'select'    => 'select',
 884      );
 885  
 886      const __EXPERIMENTAL_ELEMENT_CLASS_NAMES = array(
 887          'button'  => 'wp-element-button',
 888          'caption' => 'wp-element-caption',
 889      );
 890  
 891      /**
 892       * List of block support features that can have their related styles
 893       * generated under their own feature level selector rather than the block's.
 894       *
 895       * @since 6.1.0
 896       * @since 7.0.0 Added support for `dimensions`.
 897       * @var string[]
 898       */
 899      const BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS = array(
 900          '__experimentalBorder' => 'border',
 901          'color'                => 'color',
 902          'dimensions'           => 'dimensions',
 903          'spacing'              => 'spacing',
 904          'typography'           => 'typography',
 905      );
 906  
 907      /**
 908       * Return the input schema at the root and per origin.
 909       *
 910       * @since 6.5.0
 911       *
 912       * @param array $schema The base schema.
 913       * @return array The schema at the root and per origin.
 914       *
 915       * Example:
 916       * schema_in_root_and_per_origin(
 917       *   array(
 918       *    'fontFamily' => null,
 919       *    'slug' => null,
 920       *   )
 921       * )
 922       *
 923       * Returns:
 924       * array(
 925       *  'fontFamily' => null,
 926       *  'slug' => null,
 927       *  'default' => array(
 928       *    'fontFamily' => null,
 929       *    'slug' => null,
 930       *  ),
 931       *  'blocks' => array(
 932       *    'fontFamily' => null,
 933       *    'slug' => null,
 934       *  ),
 935       *  'theme' => array(
 936       *     'fontFamily' => null,
 937       *     'slug' => null,
 938       *  ),
 939       *  'custom' => array(
 940       *     'fontFamily' => null,
 941       *     'slug' => null,
 942       *  ),
 943       * )
 944       */
 945  	protected static function schema_in_root_and_per_origin( $schema ) {
 946          $schema_in_root_and_per_origin = $schema;
 947          foreach ( static::VALID_ORIGINS as $origin ) {
 948              $schema_in_root_and_per_origin[ $origin ] = $schema;
 949          }
 950          return $schema_in_root_and_per_origin;
 951      }
 952  
 953  
 954      /**
 955       * Processes pseudo-selectors for any node (block or variation).
 956       *
 957       * @param array  $node The node data (block or variation).
 958       * @param string $base_selector The base selector.
 959       * @param array  $settings The theme settings.
 960       * @param string $block_name The block name.
 961       * @param array|null $block_metadata Metadata about the block to get styles for.
 962       * @param array|null $style_variation Style variation metadata.
 963       * @return array Array of pseudo-selector declarations.
 964       */
 965  	private function process_pseudo_selectors( $node, $base_selector, $settings, $block_name, $block_metadata = null, $style_variation = null ) {
 966          $pseudo_declarations = array();
 967          $add_declarations    = static function ( $selector, $declarations ) use ( &$pseudo_declarations ) {
 968              if ( empty( $declarations ) ) {
 969                  return;
 970              }
 971  
 972              if ( isset( $pseudo_declarations[ $selector ] ) ) {
 973                  $pseudo_declarations[ $selector ] = array_merge(
 974                      $pseudo_declarations[ $selector ],
 975                      $declarations
 976                  );
 977              } else {
 978                  $pseudo_declarations[ $selector ] = $declarations;
 979              }
 980          };
 981  
 982          if ( ! isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_name ] ) ) {
 983              return $pseudo_declarations;
 984          }
 985  
 986          foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_name ] as $pseudo_selector ) {
 987              if ( isset( $node[ $pseudo_selector ] ) ) {
 988                  $pseudo_node = $node[ $pseudo_selector ];
 989  
 990                  if ( is_array( $block_metadata ) ) {
 991                      $feature_declarations = $this->get_feature_declarations_for_node( $block_metadata, $pseudo_node );
 992                      $feature_declarations = static::update_paragraph_text_indent_selector( $feature_declarations, $settings, $block_name );
 993                      $feature_declarations = static::update_button_width_declarations( $feature_declarations, $settings );
 994  
 995                      foreach ( $feature_declarations as $feature_selector => $declarations ) {
 996                          $target_selector   = is_array( $style_variation )
 997                              ? static::get_block_style_variation_feature_selector( $style_variation, $feature_selector )
 998                              : $feature_selector;
 999                          $combined_selector = static::append_to_selector( $target_selector, $pseudo_selector );
1000  
1001                          $add_declarations( $combined_selector, $declarations );
1002                      }
1003                  }
1004  
1005                  $combined_selector = static::append_to_selector( $base_selector, $pseudo_selector );
1006                  $declarations      = static::compute_style_properties( $pseudo_node, $settings, null, null );
1007                  $add_declarations( $combined_selector, $declarations );
1008              }
1009          }
1010  
1011          return $pseudo_declarations;
1012      }
1013  
1014  
1015      /**
1016       * Returns a class name by an element name.
1017       *
1018       * @since 6.1.0
1019       *
1020       * @param string $element The name of the element.
1021       * @return string The name of the class.
1022       */
1023  	public static function get_element_class_name( $element ) {
1024          $class_name = '';
1025  
1026          if ( isset( static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $element ] ) ) {
1027              $class_name = static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $element ];
1028          }
1029  
1030          return $class_name;
1031      }
1032  
1033      /**
1034       * Options that settings.appearanceTools enables.
1035       *
1036       * @since 6.0.0
1037       * @since 6.2.0 Added `dimensions.minHeight` and `position.sticky`.
1038       * @since 6.4.0 Added `background.backgroundImage`.
1039       * @since 6.5.0 Added `background.backgroundSize` and `dimensions.aspectRatio`.
1040       * @since 7.0.0 Added `dimensions.width` and `dimensions.height`.
1041       * @since 7.1.0 Added `background.gradient`.
1042       *              Added `dimensions.minWidth`.
1043       * @var array
1044       */
1045      const APPEARANCE_TOOLS_OPT_INS = array(
1046          array( 'background', 'backgroundImage' ),
1047          array( 'background', 'backgroundSize' ),
1048          array( 'background', 'gradient' ),
1049          array( 'border', 'color' ),
1050          array( 'border', 'radius' ),
1051          array( 'border', 'style' ),
1052          array( 'border', 'width' ),
1053          array( 'color', 'link' ),
1054          array( 'color', 'heading' ),
1055          array( 'color', 'button' ),
1056          array( 'color', 'caption' ),
1057          array( 'dimensions', 'aspectRatio' ),
1058          array( 'dimensions', 'height' ),
1059          array( 'dimensions', 'minHeight' ),
1060          array( 'dimensions', 'minWidth' ),
1061          array( 'dimensions', 'width' ),
1062          array( 'position', 'sticky' ),
1063          array( 'spacing', 'blockGap' ),
1064          array( 'spacing', 'margin' ),
1065          array( 'spacing', 'padding' ),
1066          array( 'typography', 'lineHeight' ),
1067          array( 'typography', 'textColumns' ),
1068      );
1069  
1070      /**
1071       * The latest version of the schema in use.
1072       *
1073       * @since 5.8.0
1074       * @since 5.9.0 Changed value from 1 to 2.
1075       * @since 6.6.0 Changed value from 2 to 3.
1076       * @var int
1077       */
1078      const LATEST_SCHEMA = 3;
1079  
1080      /**
1081       * Constructor.
1082       *
1083       * @since 5.8.0
1084       * @since 6.6.0 Key spacingScale by origin, and Pre-generate the spacingSizes from spacingScale.
1085       *              Added unwrapping of shared block style variations into block type variations if registered.
1086       *
1087       * @param array  $theme_json A structure that follows the theme.json schema.
1088       * @param string $origin     Optional. What source of data this object represents.
1089       *                           One of 'blocks', 'default', 'theme', or 'custom'. Default 'theme'.
1090       */
1091  	public function __construct( $theme_json = array( 'version' => self::LATEST_SCHEMA ), $origin = 'theme' ) {
1092          if ( ! in_array( $origin, static::VALID_ORIGINS, true ) ) {
1093              $origin = 'theme';
1094          }
1095  
1096          $this->theme_json    = WP_Theme_JSON_Schema::migrate( $theme_json, $origin );
1097          $blocks_metadata     = static::get_blocks_metadata();
1098          $valid_block_names   = array_keys( $blocks_metadata );
1099          $valid_element_names = array_keys( static::ELEMENTS );
1100          $valid_variations    = static::get_valid_block_style_variations( $blocks_metadata );
1101          $this->theme_json    = static::unwrap_shared_block_style_variations( $this->theme_json, $valid_variations );
1102          $this->theme_json    = static::sanitize( $this->theme_json, $valid_block_names, $valid_element_names, $valid_variations );
1103          $this->theme_json    = static::maybe_opt_in_into_settings( $this->theme_json );
1104  
1105          // Internally, presets are keyed by origin.
1106          $nodes = static::get_setting_nodes( $this->theme_json );
1107          foreach ( $nodes as $node ) {
1108              foreach ( static::PRESETS_METADATA as $preset_metadata ) {
1109                  $path = $node['path'];
1110                  foreach ( $preset_metadata['path'] as $subpath ) {
1111                      $path[] = $subpath;
1112                  }
1113                  $preset = _wp_array_get( $this->theme_json, $path, null );
1114                  if ( null !== $preset ) {
1115                      // If the preset is not already keyed by origin.
1116                      if ( isset( $preset[0] ) || empty( $preset ) ) {
1117                          _wp_array_set( $this->theme_json, $path, array( $origin => $preset ) );
1118                      }
1119                  }
1120              }
1121          }
1122  
1123          // In addition to presets, spacingScale (which generates presets) is also keyed by origin.
1124          $scale_path    = array( 'settings', 'spacing', 'spacingScale' );
1125          $spacing_scale = _wp_array_get( $this->theme_json, $scale_path, null );
1126          if ( null !== $spacing_scale ) {
1127              // If the spacingScale is not already keyed by origin.
1128              if ( empty( array_intersect( array_keys( $spacing_scale ), static::VALID_ORIGINS ) ) ) {
1129                  _wp_array_set( $this->theme_json, $scale_path, array( $origin => $spacing_scale ) );
1130              }
1131          }
1132  
1133          // Pre-generate the spacingSizes from spacingScale.
1134          $scale_path    = array( 'settings', 'spacing', 'spacingScale', $origin );
1135          $spacing_scale = _wp_array_get( $this->theme_json, $scale_path, null );
1136          if ( isset( $spacing_scale ) ) {
1137              $sizes_path           = array( 'settings', 'spacing', 'spacingSizes', $origin );
1138              $spacing_sizes        = _wp_array_get( $this->theme_json, $sizes_path, array() );
1139              $spacing_scale_sizes  = static::compute_spacing_sizes( $spacing_scale );
1140              $merged_spacing_sizes = static::merge_spacing_sizes( $spacing_scale_sizes, $spacing_sizes );
1141              _wp_array_set( $this->theme_json, $sizes_path, $merged_spacing_sizes );
1142          }
1143      }
1144  
1145      /**
1146       * Unwraps shared block style variations.
1147       *
1148       * It takes the shared variations (styles.variations.variationName) and
1149       * applies them to all the blocks that have the given variation registered
1150       * (styles.blocks.blockType.variations.variationName).
1151       *
1152       * For example, given the `core/paragraph` and `core/group` blocks have
1153       * registered the `section-a` style variation, and given the following input:
1154       *
1155       * {
1156       *   "styles": {
1157       *     "variations": {
1158       *       "section-a": { "color": { "background": "backgroundColor" } }
1159       *     }
1160       *   }
1161       * }
1162       *
1163       * It returns the following output:
1164       *
1165       * {
1166       *   "styles": {
1167       *     "blocks": {
1168       *       "core/paragraph": {
1169       *         "variations": {
1170       *             "section-a": { "color": { "background": "backgroundColor" } }
1171       *         },
1172       *       },
1173       *       "core/group": {
1174       *         "variations": {
1175       *           "section-a": { "color": { "background": "backgroundColor" } }
1176       *         }
1177       *       }
1178       *     }
1179       *   }
1180       * }
1181       *
1182       * @since 6.6.0
1183       *
1184       * @param array $theme_json       A structure that follows the theme.json schema.
1185       * @param array $valid_variations Valid block style variations.
1186       * @return array Theme json data with shared variation definitions unwrapped under appropriate block types.
1187       */
1188  	private static function unwrap_shared_block_style_variations( $theme_json, $valid_variations ) {
1189          if ( empty( $theme_json['styles']['variations'] ) || empty( $valid_variations ) ) {
1190              return $theme_json;
1191          }
1192  
1193          $new_theme_json = $theme_json;
1194          $variations     = $new_theme_json['styles']['variations'];
1195  
1196          foreach ( $valid_variations as $block_type => $registered_variations ) {
1197              foreach ( $registered_variations as $variation_name ) {
1198                  $block_level_data = $new_theme_json['styles']['blocks'][ $block_type ]['variations'][ $variation_name ] ?? array();
1199                  $top_level_data   = $variations[ $variation_name ] ?? array();
1200                  $merged_data      = array_replace_recursive( $top_level_data, $block_level_data );
1201                  if ( ! empty( $merged_data ) ) {
1202                      _wp_array_set( $new_theme_json, array( 'styles', 'blocks', $block_type, 'variations', $variation_name ), $merged_data );
1203                  }
1204              }
1205          }
1206  
1207          unset( $new_theme_json['styles']['variations'] );
1208  
1209          return $new_theme_json;
1210      }
1211  
1212      /**
1213       * Enables some opt-in settings if theme declared support.
1214       *
1215       * @since 5.9.0
1216       *
1217       * @param array $theme_json A theme.json structure to modify.
1218       * @return array The modified theme.json structure.
1219       */
1220  	protected static function maybe_opt_in_into_settings( $theme_json ) {
1221          $new_theme_json = $theme_json;
1222  
1223          if (
1224              isset( $new_theme_json['settings']['appearanceTools'] ) &&
1225              true === $new_theme_json['settings']['appearanceTools']
1226          ) {
1227              static::do_opt_in_into_settings( $new_theme_json['settings'] );
1228          }
1229  
1230          if ( isset( $new_theme_json['settings']['blocks'] ) && is_array( $new_theme_json['settings']['blocks'] ) ) {
1231              foreach ( $new_theme_json['settings']['blocks'] as &$block ) {
1232                  if ( isset( $block['appearanceTools'] ) && ( true === $block['appearanceTools'] ) ) {
1233                      static::do_opt_in_into_settings( $block );
1234                  }
1235              }
1236          }
1237  
1238          return $new_theme_json;
1239      }
1240  
1241      /**
1242       * Enables some settings.
1243       *
1244       * @since 5.9.0
1245       *
1246       * @param array $context The context to which the settings belong.
1247       */
1248  	protected static function do_opt_in_into_settings( &$context ) {
1249          foreach ( static::APPEARANCE_TOOLS_OPT_INS as $path ) {
1250              /*
1251               * Use "unset prop" as a marker instead of "null" because
1252               * "null" can be a valid value for some props (e.g. blockGap).
1253               */
1254              if ( 'unset prop' === _wp_array_get( $context, $path, 'unset prop' ) ) {
1255                  _wp_array_set( $context, $path, true );
1256              }
1257          }
1258  
1259          unset( $context['appearanceTools'] );
1260      }
1261  
1262      /**
1263       * Sanitizes the input according to the schemas.
1264       *
1265       * @since 5.8.0
1266       * @since 5.9.0 Added the `$valid_block_names` and `$valid_element_name` parameters.
1267       * @since 6.3.0 Added the `$valid_variations` parameter.
1268       * @since 6.6.0 Updated schema to allow extended block style variations.
1269       *
1270       * @param array $input               Structure to sanitize.
1271       * @param array $valid_block_names   List of valid block names.
1272       * @param array $valid_element_names List of valid element names.
1273       * @param array $valid_variations    List of valid variations per block.
1274       * @return array The sanitized output.
1275       */
1276  	protected static function sanitize( $input, $valid_block_names, $valid_element_names, $valid_variations ) {
1277          $output = array();
1278  
1279          if ( ! is_array( $input ) ) {
1280              return $output;
1281          }
1282  
1283          // Preserve only the top most level keys.
1284          $output = array_intersect_key( $input, array_flip( static::VALID_TOP_LEVEL_KEYS ) );
1285  
1286          /*
1287           * Remove any rules that are annotated as "top" in VALID_STYLES constant.
1288           * Some styles are only meant to be available at the top-level (e.g.: blockGap),
1289           * hence, the schema for blocks & elements should not have them.
1290           */
1291          $styles_non_top_level = static::VALID_STYLES;
1292          foreach ( array_keys( $styles_non_top_level ) as $section ) {
1293              // array_key_exists() needs to be used instead of isset() because the value can be null.
1294              if ( array_key_exists( $section, $styles_non_top_level ) && is_array( $styles_non_top_level[ $section ] ) ) {
1295                  foreach ( array_keys( $styles_non_top_level[ $section ] ) as $prop ) {
1296                      if ( 'top' === $styles_non_top_level[ $section ][ $prop ] ) {
1297                          unset( $styles_non_top_level[ $section ][ $prop ] );
1298                      }
1299                  }
1300              }
1301          }
1302  
1303          // Build the schema based on valid block & element names.
1304          $schema                   = array();
1305          $schema_styles_elements   = array();
1306          $responsive_media_queries = static::get_viewport_media_queries( $input['settings']['viewport'] ?? null );
1307  
1308          /*
1309           * Set allowed element pseudo selectors and responsive breakpoint states.
1310           * Target data structure in schema:
1311           * e.g.
1312           * - top level elements: `$schema['styles']['elements']['link'][':hover']`.
1313           * - block level elements: `$schema['styles']['blocks']['core/button']['elements']['link'][':hover']`.
1314           * - block responsive elements: `$schema['styles']['blocks']['core/button']['@tablet']['elements']['link'][':hover']`.
1315           */
1316          foreach ( $valid_element_names as $element ) {
1317              $schema_styles_elements[ $element ] = $styles_non_top_level;
1318  
1319              if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) {
1320                  foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
1321                      $schema_styles_elements[ $element ][ $pseudo_selector ] = $styles_non_top_level;
1322                  }
1323              }
1324  
1325              // Add responsive breakpoint states for elements.
1326              foreach ( array_keys( $responsive_media_queries ) as $breakpoint_state ) {
1327                  $schema_styles_elements[ $element ][ $breakpoint_state ] = $styles_non_top_level;
1328              }
1329          }
1330  
1331          $schema_styles_blocks   = array();
1332          $schema_settings_blocks = array();
1333  
1334          /*
1335           * Generate a schema for blocks.
1336           * - Block styles can contain `elements`, `variations`, and responsive breakpoint state definitions.
1337           * - Variations definitions cannot be nested.
1338           * - Variations can contain styles for inner `blocks`, `elements`, and responsive breakpoint states.
1339           * - Variation inner `blocks` styles can contain `elements` and responsive breakpoint states.
1340           *
1341           * As each variation needs both a `blocks` schema and responsive `blocks` schemas
1342           * for further nested inner `blocks`, the overall schema is generated in multiple passes.
1343           */
1344          foreach ( $valid_block_names as $block ) {
1345              $schema_settings_blocks[ $block ] = static::VALID_SETTINGS;
1346              // `viewport` and `blockVisibility` are global-only settings and cannot be set per block for now.
1347              unset( $schema_settings_blocks[ $block ]['viewport'] );
1348              unset( $schema_settings_blocks[ $block ]['blockVisibility'] );
1349              $schema_styles_blocks[ $block ]             = $styles_non_top_level;
1350              $schema_styles_blocks[ $block ]['elements'] = $schema_styles_elements;
1351  
1352              // Add responsive breakpoint states for all blocks.
1353              foreach ( array_keys( $responsive_media_queries ) as $breakpoint_state ) {
1354                  $schema_styles_blocks[ $block ][ $breakpoint_state ]             = $styles_non_top_level;
1355                  $schema_styles_blocks[ $block ][ $breakpoint_state ]['elements'] = $schema_styles_elements;
1356  
1357                  if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] ) ) {
1358                      foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] as $pseudo_selector ) {
1359                          $schema_styles_blocks[ $block ][ $breakpoint_state ][ $pseudo_selector ] = $styles_non_top_level;
1360                      }
1361                  }
1362              }
1363  
1364              // Add pseudo-selectors for blocks that support them
1365              if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] ) ) {
1366                  foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] as $pseudo_selector ) {
1367                      $schema_styles_blocks[ $block ][ $pseudo_selector ] = $styles_non_top_level;
1368                  }
1369              }
1370  
1371              // Add custom states for blocks that support them (e.g. '-current' for navigation).
1372              if ( isset( static::VALID_BLOCK_CUSTOM_STATES[ $block ] ) ) {
1373                  foreach ( static::VALID_BLOCK_CUSTOM_STATES[ $block ] as $custom_state ) {
1374                      $custom_state_schema = $styles_non_top_level;
1375                      /*
1376                       * The same pseudo-selectors valid for the block at the top level
1377                       * are also valid within each custom state.
1378                       */
1379                      if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] ) ) {
1380                          foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] as $pseudo ) {
1381                              $custom_state_schema[ $pseudo ] = $styles_non_top_level;
1382                          }
1383                      }
1384                      $schema_styles_blocks[ $block ][ $custom_state ] = $custom_state_schema;
1385                  }
1386              }
1387          }
1388  
1389          $block_style_variation_styles             = static::VALID_STYLES;
1390          $block_style_variation_styles['blocks']   = $schema_styles_blocks;
1391          $block_style_variation_styles['elements'] = $schema_styles_elements;
1392  
1393          foreach ( $valid_block_names as $block ) {
1394              // Build the schema for each block style variation.
1395              $style_variation_names = array();
1396              if (
1397                  ! empty( $input['styles']['blocks'][ $block ]['variations'] ) &&
1398                  is_array( $input['styles']['blocks'][ $block ]['variations'] ) &&
1399                  isset( $valid_variations[ $block ] )
1400              ) {
1401                  $style_variation_names = array_intersect(
1402                      array_keys( $input['styles']['blocks'][ $block ]['variations'] ),
1403                      $valid_variations[ $block ]
1404                  );
1405              }
1406  
1407              $schema_styles_variations = array();
1408              if ( ! empty( $style_variation_names ) ) {
1409                  foreach ( $style_variation_names as $variation_name ) {
1410                      $variation_schema = $block_style_variation_styles;
1411  
1412                      // Add responsive breakpoint states to block style variations.
1413                      foreach ( array_keys( $responsive_media_queries ) as $breakpoint_state ) {
1414                          $variation_schema[ $breakpoint_state ]             = $styles_non_top_level;
1415                          $variation_schema[ $breakpoint_state ]['elements'] = $schema_styles_elements;
1416                          $variation_schema[ $breakpoint_state ]['blocks']   = $schema_styles_blocks;
1417  
1418                          if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] ) ) {
1419                              foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] as $pseudo_selector ) {
1420                                  $variation_schema[ $breakpoint_state ][ $pseudo_selector ] = $styles_non_top_level;
1421                              }
1422                          }
1423                      }
1424  
1425                      // Add pseudo-selectors to variations for blocks that support them
1426                      if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] ) ) {
1427                          foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block ] as $pseudo_selector ) {
1428                              $variation_schema[ $pseudo_selector ] = $styles_non_top_level;
1429                          }
1430                      }
1431  
1432                      $schema_styles_variations[ $variation_name ] = $variation_schema;
1433                  }
1434              }
1435  
1436              $schema_styles_blocks[ $block ]['variations'] = $schema_styles_variations;
1437          }
1438  
1439          $schema['styles']                                 = static::VALID_STYLES;
1440          $schema['styles']['blocks']                       = $schema_styles_blocks;
1441          $schema['styles']['elements']                     = $schema_styles_elements;
1442          $schema['settings']                               = static::VALID_SETTINGS;
1443          $schema['settings']['blocks']                     = $schema_settings_blocks;
1444          $schema['settings']['typography']['fontFamilies'] = static::schema_in_root_and_per_origin( static::FONT_FAMILY_SCHEMA );
1445  
1446          // Remove anything that's not present in the schema.
1447          foreach ( array( 'styles', 'settings' ) as $subtree ) {
1448              if ( ! isset( $input[ $subtree ] ) ) {
1449                  continue;
1450              }
1451  
1452              if ( ! is_array( $input[ $subtree ] ) ) {
1453                  unset( $output[ $subtree ] );
1454                  continue;
1455              }
1456  
1457              $result = static::remove_keys_not_in_schema( $input[ $subtree ], $schema[ $subtree ] );
1458  
1459              if ( 'settings' === $subtree && array_key_exists( 'viewport', $input[ $subtree ] ) ) {
1460                  $result['viewport'] = static::sanitize_viewport_settings( $input[ $subtree ]['viewport'] );
1461              }
1462  
1463              if ( empty( $result ) ) {
1464                  unset( $output[ $subtree ] );
1465              } else {
1466                  $output[ $subtree ] = static::resolve_custom_css_format( $result );
1467              }
1468          }
1469  
1470          return $output;
1471      }
1472  
1473      /**
1474       * Appends a sub-selector to an existing one.
1475       *
1476       * Given the compounded $selector "h1, h2, h3"
1477       * and the $to_append selector ".some-class" the result will be
1478       * "h1.some-class, h2.some-class, h3.some-class".
1479       *
1480       * @since 5.8.0
1481       * @since 6.1.0 Added append position.
1482       * @since 6.3.0 Removed append position parameter.
1483       *
1484       * @param string $selector  Original selector.
1485       * @param string $to_append Selector to append.
1486       * @return string The new selector.
1487       */
1488  	protected static function append_to_selector( $selector, $to_append ) {
1489          if ( ! str_contains( $selector, ',' ) ) {
1490              return trim( $selector, " \t\n" ) . $to_append;
1491          }
1492  
1493          /**
1494           * Check for an opportunity to skip the more-costly selector splitting.
1495           * This should be possible if there are no comments, strings, functions,
1496           * URLs, escapes, or comment declaration openers (CDOs).
1497           *
1498           * Note that this means the fast-path will not apply for selectors like
1499           * the following incomplete list:
1500           *
1501           *  - `[class ~= "wide"]`
1502           *  - `.wp-block:is(.is-style-a, .is-style-b)`
1503           *  - `:nth-child(1)`
1504           *
1505           * These syntax forms all present opportunities where a comma may not
1506           * separate selectors. If none of the start characters are present,
1507           * there should be no way for a comma to mean anything other than a
1508           * comma token. The exception are syntax errors, which are not handled here.
1509           *
1510           * @see https://www.w3.org/TR/css-syntax-3/#parse-comma-separated-list-of-component-values
1511           */
1512          if ( strlen( $selector ) === strcspn( $selector, '/\'"(<\\' ) ) {
1513              return preg_replace( '~[ \t\n]*,[ \t\n]*~', "{$to_append}, ", trim( $selector, " \t\n" ) ) . $to_append;
1514          }
1515  
1516          $new_selectors = array();
1517          $selectors     = static::split_selector_list( $selector );
1518          foreach ( $selectors as $sel ) {
1519              $new_selectors[] = $sel . $to_append;
1520          }
1521          return implode( ', ', $new_selectors );
1522      }
1523  
1524      /**
1525       * Prepends a sub-selector to an existing one.
1526       *
1527       * Given the compounded $selector "h1, h2, h3"
1528       * and the $to_prepend selector ".some-class " the result will be
1529       * ".some-class h1, .some-class  h2, .some-class  h3".
1530       *
1531       * @since 6.3.0
1532       *
1533       * @param string $selector   Original selector.
1534       * @param string $to_prepend Selector to prepend.
1535       * @return string The new selector.
1536       */
1537  	protected static function prepend_to_selector( $selector, $to_prepend ) {
1538          if ( ! str_contains( $selector, ',' ) ) {
1539              return $to_prepend . trim( $selector, " \t\n" );
1540          }
1541  
1542          /**
1543           * Check for an opportunity to skip the more-costly selector splitting.
1544           * This should be possible if there are no comments, strings, functions,
1545           * URLs, escapes, or comment declaration openers (CDOs).
1546           *
1547           * Note that this means the fast-path will not apply for selectors like
1548           * the following incomplete list:
1549           *
1550           *  - `[class ~= "wide"]`
1551           *  - `.wp-block:is(.is-style-a, .is-style-b)`
1552           *  - `:nth-child(1)`
1553           *
1554           * These syntax forms all present opportunities where a comma may not
1555           * separate selectors. If none of the start characters are present,
1556           * there should be no way for a comma to mean anything other than a
1557           * comma token. The exception are syntax errors, which are not handled here.
1558           *
1559           * @see https://www.w3.org/TR/css-syntax-3/#parse-comma-separated-list-of-component-values
1560           */
1561          if ( strlen( $selector ) === strcspn( $selector, '/\'"(<\\' ) ) {
1562              return $to_prepend . preg_replace( '~[ \t\n]*,[ \t\n]*~', ", {$to_prepend}", trim( $selector, " \t\n" ) );
1563          }
1564  
1565          $new_selectors = array();
1566          $selectors     = static::split_selector_list( $selector );
1567          foreach ( $selectors as $sel ) {
1568              $new_selectors[] = $to_prepend . $sel;
1569          }
1570          return implode( ', ', $new_selectors );
1571      }
1572  
1573      /**
1574       * Splits a selector list into separate selectors.
1575       *
1576       * While selectors are joined by commas, not all commas separate top-level selectors.
1577       * This method only separates top-level selectors, so some commas may appear inside
1578       * strings, nested selectors, and comments. Leading and trailing CSS whitespace is
1579       * trimmed from the returned list items.
1580       *
1581       * Non-selector content, such as comments, are retained in the list in the same item
1582       * as the selector content they follow.
1583       *
1584       * Example:
1585       *
1586       *     array( '.wp-block' )    === self::split_selector_list( '.wp-block' );
1587       *     array( '.one', '.two' ) === self::split_selector_list( '.one, .two' );
1588       *
1589       *     // Nested selector lists are retained within their containing selector.
1590       *     array( ':is(.a, .b)', 'c' ) === self::split_selector_list( ':is(.a, .b), .c' );
1591       *
1592       *     // Commas within strings do not separate selectors.
1593       *     $selectors   = self::split_selector_list( '[data-label="Save, continue"],.fallback' );
1594       *     $selectors === array( '[data-label="Save, continue"]', '.fallback' )
1595       *
1596       *     array( 'lang(zh, "*-hant")', '.foo' ) === self::split_selector_list( 'lang(zh, "*-hant"), .foo' );
1597       *
1598       *     // Identifiers may contain escaped commas.
1599       *     array( '.foo\,bar', '.baz' ) === self::split_selector_list( '.foo\,bar,.baz' );
1600       *
1601       *     // Comments stay with the selector they follow.
1602       *     array( '.a /* a, the first *\/', '.b' ) === self::split_selector_list( '.a /* a, the first *\/,.b' );
1603       *
1604       * @see https://www.w3.org/TR/selectors/#parse-selector
1605       * @see https://www.w3.org/TR/css-syntax-3/
1606       *
1607       * @since 7.1.0
1608       *
1609       * @param string $selector CSS selector list as a string, e.g. '.wp-block .wp-block-paragraph'.
1610       * @return string[] List of trimmed selectors parsed from input list.
1611       */
1612  	protected static function split_selector_list( $selector ): array {
1613          if ( ! str_contains( $selector, ',' ) ) {
1614              // See note on trimming CSS whitespace in main loop.
1615              return array( trim( $selector, " \t\n" ) );
1616          }
1617  
1618          $selectors         = array();
1619          $selector_length   = strlen( $selector );
1620          $parentheses_depth = 0;
1621          $at                = 0;
1622          $was_at            = 0;
1623  
1624          while ( $at < $selector_length ) {
1625              $next_at = $at + strcspn( $selector, '/,\'"()<-\\', $at );
1626              if ( $next_at >= $selector_length ) {
1627                  break;
1628              }
1629  
1630              $next_cp = $selector[ $next_at ];
1631  
1632              // Escaped syntax characters do not act as delimiters.
1633              if ( '\\' === $next_cp ) {
1634                  $at = min( $next_at + 2, $selector_length );
1635                  continue;
1636              }
1637  
1638              /*
1639               * Start of a parenthesized expression, which maintains a stack of parentheses.
1640               * For the sake of this function, no selector list will be split inside parentheses.
1641               * Therefore it’s possible to jump ahead until this list completes.
1642               */
1643              if ( '(' === $next_cp || ')' === $next_cp ) {
1644                  $parentheses_depth += '(' === $next_cp ? 1 : -1;
1645                  $at                 = $next_at + 1;
1646                  continue;
1647              }
1648  
1649              // Start of a string, which will be incorporated into the selector in which it’s found.
1650              if ( "'" === $next_cp || '"' === $next_cp ) {
1651                  $end_of_string = $next_at + 1;
1652                  while ( $end_of_string < $selector_length ) {
1653                      $end_of_string += strcspn( $selector, "{$next_cp}\\", $end_of_string );
1654                      if ( $end_of_string >= $selector_length ) {
1655                          break;
1656                      }
1657  
1658                      $end_cp = $selector[ $end_of_string ];
1659  
1660                      // Skip escaped characters.
1661                      if ( '\\' === $end_cp ) {
1662                          $end_of_string = $end_of_string + 2;
1663                          continue;
1664                      }
1665  
1666                      if ( $next_cp === $end_cp ) {
1667                          ++$end_of_string;
1668                          break;
1669                      }
1670  
1671                      ++$end_of_string;
1672                  }
1673  
1674                  $at = $end_of_string;
1675                  continue;
1676              }
1677  
1678              // Start of a comment, which will be incorporated into the selector in which it’s found.
1679              if ( '/' === $next_cp && ( $next_at + 1 ) < $selector_length && '*' === $selector[ $next_at + 1 ] ) {
1680                  $comment_end_at = strpos( $selector, '*/', $next_at + 1 );
1681                  $is_terminated  = false !== $comment_end_at;
1682                  $after_comment  = $is_terminated ? $comment_end_at + 2 : strlen( $selector );
1683                  $at             = $after_comment;
1684                  continue;
1685              }
1686  
1687              // Start of a CDO or CDC, which will be incorporated into the selector in which it’s found.
1688              if (
1689                  ( '<' === $next_cp && 0 === substr_compare( $selector, '<!--', $next_at, 4 ) ) ||
1690                  ( '-' === $next_cp && 0 === substr_compare( $selector, '-->', $next_at, 3 ) )
1691              ) {
1692                  $at = $next_at + ( '<' === $next_cp ? 4 : 3 );
1693                  continue;
1694              }
1695  
1696              // Everything else is either a comma token or part of a selector.
1697              if ( ',' === $next_cp && 0 === $parentheses_depth ) {
1698                  /**
1699                   * Trim each selector so that downstream code doesn’t see whitespace
1700                   * as the first character in a selector and get confused.
1701                   *
1702                   * There is inconsistency in this because comments and other syntax
1703                   * are included which are also not part of the selector itself, but
1704                   * a tradeoff is made between removing common syntax which carries
1705                   * no meaning and rarer syntax which leaves auxiliary information.
1706                   *
1707                   * > A newline, U+0009 CHARACTER TABULATION, or U+0020 SPACE.
1708                   * > Note that U+000D CARRIAGE RETURN and U+000C FORM FEED are
1709                   * > not included in this definition, as they are converted
1710                   * > to U+000A LINE FEED during preprocessing.
1711                   *
1712                   * @see https://www.w3.org/TR/css-syntax/#whitespace
1713                   * @see https://www.w3.org/TR/css-syntax/#newline
1714                   */
1715                  $selectors[] = trim( substr( $selector, $was_at, $next_at - $was_at ), " \t\n" );
1716                  $at          = $next_at + 1;
1717                  $was_at      = $at;
1718                  continue;
1719              }
1720  
1721              $at = $next_at + 1;
1722          }
1723  
1724          if ( $was_at < $selector_length ) {
1725              // See note on trimming CSS whitespace in main loop.
1726              $selectors[] = trim( substr( $selector, $was_at ), " \t\n" );
1727          }
1728  
1729          return $selectors;
1730      }
1731  
1732      /**
1733       * Returns the metadata for each block.
1734       *
1735       * Example:
1736       *
1737       *     {
1738       *       'core/paragraph': {
1739       *         'selector': 'p',
1740       *         'elements': {
1741       *           'link' => 'link selector',
1742       *           'etc'  => 'element selector'
1743       *         }
1744       *       },
1745       *       'core/heading': {
1746       *         'selector': 'h1',
1747       *         'elements': {}
1748       *       },
1749       *       'core/image': {
1750       *         'selector': '.wp-block-image',
1751       *         'duotone': 'img',
1752       *         'elements': {}
1753       *       }
1754       *     }
1755       *
1756       * @since 5.8.0
1757       * @since 5.9.0 Added `duotone` key with CSS selector.
1758       * @since 6.1.0 Added `features` key with block support feature level selectors.
1759       * @since 6.3.0 Refactored and stabilized selectors API.
1760       * @since 6.6.0 Updated to include block style variations from the block styles registry.
1761       *
1762       * @return array Block metadata.
1763       */
1764  	protected static function get_blocks_metadata() {
1765          $registry       = WP_Block_Type_Registry::get_instance();
1766          $blocks         = $registry->get_all_registered();
1767          $style_registry = WP_Block_Styles_Registry::get_instance();
1768  
1769          // Is there metadata for all currently registered blocks?
1770          $blocks = array_diff_key( $blocks, static::$blocks_metadata );
1771          if ( empty( $blocks ) ) {
1772              /*
1773               * New block styles may have been registered within WP_Block_Styles_Registry.
1774               * Update block metadata for any new block style variations.
1775               */
1776              $registered_styles = $style_registry->get_all_registered();
1777              foreach ( static::$blocks_metadata as $block_name => $block_metadata ) {
1778                  if ( ! empty( $registered_styles[ $block_name ] ) ) {
1779                      $style_selectors = $block_metadata['styleVariations'] ?? array();
1780  
1781                      foreach ( $registered_styles[ $block_name ] as $block_style ) {
1782                          if ( ! isset( $style_selectors[ $block_style['name'] ] ) ) {
1783                              $style_selectors[ $block_style['name'] ] = static::get_block_style_variation_selector( $block_style['name'], $block_metadata['selector'] );
1784                          }
1785                      }
1786  
1787                      static::$blocks_metadata[ $block_name ]['styleVariations'] = $style_selectors;
1788                  }
1789              }
1790              return static::$blocks_metadata;
1791          }
1792  
1793          foreach ( $blocks as $block_name => $block_type ) {
1794              $root_selector = wp_get_block_css_selector( $block_type );
1795  
1796              static::$blocks_metadata[ $block_name ]['selector']  = $root_selector;
1797              static::$blocks_metadata[ $block_name ]['selectors'] = static::get_block_selectors( $block_type, $root_selector );
1798  
1799              $elements = static::get_block_element_selectors( $root_selector );
1800              if ( ! empty( $elements ) ) {
1801                  static::$blocks_metadata[ $block_name ]['elements'] = $elements;
1802              }
1803  
1804              // The block may or may not have a duotone selector.
1805              $duotone_selector = wp_get_block_css_selector( $block_type, 'filter.duotone' );
1806  
1807              // Keep backwards compatibility for support.color.__experimentalDuotone.
1808              if ( null === $duotone_selector ) {
1809                  $duotone_support = $block_type->supports['color']['__experimentalDuotone'] ?? null;
1810  
1811                  if ( $duotone_support ) {
1812                      $root_selector    = wp_get_block_css_selector( $block_type );
1813                      $duotone_selector = static::scope_selector( $root_selector, $duotone_support );
1814                  }
1815              }
1816  
1817              if ( null !== $duotone_selector ) {
1818                  static::$blocks_metadata[ $block_name ]['duotone'] = $duotone_selector;
1819              }
1820  
1821              // If the block has style variations, append their selectors to the block metadata.
1822              $style_selectors = array();
1823              if ( ! empty( $block_type->styles ) ) {
1824                  foreach ( $block_type->styles as $style ) {
1825                      $style_selectors[ $style['name'] ] = static::get_block_style_variation_selector( $style['name'], static::$blocks_metadata[ $block_name ]['selector'] );
1826                  }
1827              }
1828  
1829              // Block style variations can be registered through the WP_Block_Styles_Registry as well as block.json.
1830              $registered_styles = $style_registry->get_registered_styles_for_block( $block_name );
1831              foreach ( $registered_styles as $style ) {
1832                  $style_selectors[ $style['name'] ] = static::get_block_style_variation_selector( $style['name'], static::$blocks_metadata[ $block_name ]['selector'] );
1833              }
1834  
1835              if ( ! empty( $style_selectors ) ) {
1836                  static::$blocks_metadata[ $block_name ]['styleVariations'] = $style_selectors;
1837              }
1838  
1839              // If the block has custom states defined in block.json, store their selectors.
1840              if ( ! empty( $block_type->selectors['states'] ) && is_array( $block_type->selectors['states'] ) ) {
1841                  static::$blocks_metadata[ $block_name ]['states'] = $block_type->selectors['states'];
1842              }
1843          }
1844  
1845          return static::$blocks_metadata;
1846      }
1847  
1848      /**
1849       * Given a tree, removes the keys that are not present in the schema.
1850       *
1851       * It is recursive and modifies the input in-place.
1852       *
1853       * @since 5.8.0
1854       * @since 7.0.0 Added type validation for boolean values.
1855       *
1856       * @param array $tree   Input to process.
1857       * @param array $schema Schema to adhere to.
1858       * @return array The modified $tree.
1859       */
1860  	protected static function remove_keys_not_in_schema( $tree, $schema ) {
1861          if ( ! is_array( $tree ) ) {
1862              return $tree;
1863          }
1864  
1865          foreach ( $tree as $key => $value ) {
1866              // Remove keys not in the schema or with null/empty values.
1867              if ( ! array_key_exists( $key, $schema ) ) {
1868                  unset( $tree[ $key ] );
1869                  continue;
1870              }
1871  
1872              // Validate type if schema specifies a boolean marker.
1873              if ( is_bool( $schema[ $key ] ) ) {
1874                  // Schema expects a boolean value - validate the input matches.
1875                  if ( ! is_bool( $value ) ) {
1876                      unset( $tree[ $key ] );
1877                      continue;
1878                  }
1879                  // Type matches, keep the value and continue to next key.
1880                  continue;
1881              }
1882  
1883              if ( is_array( $schema[ $key ] ) ) {
1884                  if ( ! is_array( $value ) ) {
1885                      unset( $tree[ $key ] );
1886                  } elseif ( wp_is_numeric_array( $value ) ) {
1887                      // If indexed, process each item in the array.
1888                      foreach ( $value as $item_key => $item_value ) {
1889                          if ( isset( $schema[ $key ][0] ) && is_array( $schema[ $key ][0] ) ) {
1890                              $tree[ $key ][ $item_key ] = self::remove_keys_not_in_schema( $item_value, $schema[ $key ][0] );
1891                          } else {
1892                              // If the schema does not define a further structure, keep the value as is.
1893                              $tree[ $key ][ $item_key ] = $item_value;
1894                          }
1895                      }
1896                  } else {
1897                      // If associative, process as a single object.
1898                      $tree[ $key ] = self::remove_keys_not_in_schema( $value, $schema[ $key ] );
1899  
1900                      if ( empty( $tree[ $key ] ) ) {
1901                          unset( $tree[ $key ] );
1902                      }
1903                  }
1904              }
1905          }
1906          return $tree;
1907      }
1908  
1909      /**
1910       * Returns the existing settings for each block.
1911       *
1912       * Example:
1913       *
1914       *     {
1915       *       'root': {
1916       *         'color': {
1917       *           'custom': true
1918       *         }
1919       *       },
1920       *       'core/paragraph': {
1921       *         'spacing': {
1922       *           'customPadding': true
1923       *         }
1924       *       }
1925       *     }
1926       *
1927       * @since 5.8.0
1928       *
1929       * @return array Settings per block.
1930       */
1931  	public function get_settings() {
1932          if ( ! isset( $this->theme_json['settings'] ) ) {
1933              return array();
1934          } else {
1935              return $this->theme_json['settings'];
1936          }
1937      }
1938  
1939      /**
1940       * Returns the stylesheet that results of processing
1941       * the theme.json structure this object represents.
1942       *
1943       * @since 5.8.0
1944       * @since 5.9.0 Removed the `$type` parameter, added the `$types` and `$origins` parameters.
1945       * @since 6.3.0 Add fallback layout styles for Post Template when block gap support isn't available.
1946       * @since 6.6.0 Added boolean `skip_root_layout_styles` and `include_block_style_variations` options
1947       *              to control styles output as desired.
1948       * @since 7.0.0 Deprecated 'base-layout-styles' type; added `base_layout_styles` option for classic themes.
1949       *
1950       * @param string[] $types   Types of styles to load. Will load all by default. It accepts:
1951       *                          - `variables`: only the CSS Custom Properties for presets & custom ones.
1952       *                          - `styles`: only the styles section in theme.json.
1953       *                          - `presets`: only the classes for the presets.
1954       *                          - `base-layout-styles`: only the base layout styles. Deprecated in 7.0.0.
1955       *                          - `custom-css`: only the custom CSS.
1956       * @param string[] $origins A list of origins to include. By default it includes VALID_ORIGINS.
1957       * @param array    $options {
1958       *     Optional. An array of options for now used for internal purposes only (may change without notice).
1959       *
1960       *     @type string $scope                           Makes sure all style are scoped to a given selector
1961       *     @type string $root_selector                   Overwrites and forces a given selector to be used on the root node
1962       *     @type bool   $skip_root_layout_styles         Omits root layout styles from the generated stylesheet. Default false.
1963       *     @type bool   $base_layout_styles              When true generates only base layout styles without alignment rules. Default false.
1964       *     @type bool   $include_block_style_variations  Includes styles for block style variations in the generated stylesheet. Default false.
1965       * }
1966       * @return string The resulting stylesheet.
1967       */
1968  	public function get_stylesheet( $types = array( 'variables', 'styles', 'presets' ), $origins = null, $options = array() ) {
1969          if ( null === $origins ) {
1970              $origins = static::VALID_ORIGINS;
1971          }
1972  
1973          if ( is_string( $types ) ) {
1974              // Dispatch error and map old arguments to new ones.
1975              _deprecated_argument( __FUNCTION__, '5.9.0' );
1976              if ( 'block_styles' === $types ) {
1977                  $types = array( 'styles', 'presets' );
1978              } elseif ( 'css_variables' === $types ) {
1979                  $types = array( 'variables' );
1980              } else {
1981                  $types = array( 'variables', 'styles', 'presets' );
1982              }
1983          }
1984  
1985          $blocks_metadata = static::get_blocks_metadata();
1986          $style_nodes     = static::get_style_nodes( $this->theme_json, $blocks_metadata, $options );
1987          $setting_nodes   = static::get_setting_nodes( $this->theme_json, $blocks_metadata );
1988  
1989          $root_style_key    = array_search( static::ROOT_BLOCK_SELECTOR, array_column( $style_nodes, 'selector' ), true );
1990          $root_settings_key = array_search( static::ROOT_BLOCK_SELECTOR, array_column( $setting_nodes, 'selector' ), true );
1991  
1992          if ( ! empty( $options['scope'] ) ) {
1993              foreach ( $setting_nodes as &$node ) {
1994                  $node['selector'] = static::scope_selector( $options['scope'], $node['selector'] );
1995              }
1996              foreach ( $style_nodes as &$node ) {
1997                  $node = static::scope_style_node_selectors( $options['scope'], $node );
1998              }
1999              unset( $node );
2000          }
2001  
2002          if ( ! empty( $options['root_selector'] ) ) {
2003              if ( false !== $root_settings_key ) {
2004                  $setting_nodes[ $root_settings_key ]['selector'] = $options['root_selector'];
2005              }
2006              if ( false !== $root_style_key ) {
2007                  $style_nodes[ $root_style_key ]['selector'] = $options['root_selector'];
2008              }
2009          }
2010  
2011          $stylesheet = '';
2012  
2013          if ( in_array( 'variables', $types, true ) ) {
2014              $stylesheet .= $this->get_css_variables( $setting_nodes, $origins );
2015          }
2016  
2017          if ( in_array( 'styles', $types, true ) ) {
2018              if ( false !== $root_style_key && empty( $options['skip_root_layout_styles'] ) ) {
2019                  $stylesheet .= $this->get_root_layout_rules( $style_nodes[ $root_style_key ]['selector'], $style_nodes[ $root_style_key ], $options );
2020              }
2021              $stylesheet .= $this->get_block_classes( $style_nodes );
2022          }
2023  
2024          if ( in_array( 'presets', $types, true ) ) {
2025              $stylesheet .= $this->get_preset_classes( $setting_nodes, $origins );
2026          }
2027  
2028          // Load the custom CSS last so it has the highest specificity.
2029          if ( in_array( 'custom-css', $types, true ) ) {
2030              // Add the global styles root CSS.
2031              $stylesheet .= _wp_array_get( $this->theme_json, array( 'styles', 'css' ) );
2032          }
2033  
2034          return $stylesheet;
2035      }
2036  
2037      /**
2038       * Processes the CSS, to apply nesting.
2039       *
2040       * @since 6.2.0
2041       * @since 6.6.0 Enforced 0-1-0 specificity for block custom CSS selectors.
2042       * @since 7.0.0 Made public for use in custom-css block support.
2043       *
2044       * @param string $css      The CSS to process.
2045       * @param string $selector The selector to nest.
2046       * @return string The processed CSS.
2047       */
2048  	public static function process_blocks_custom_css( $css, $selector ) {
2049          $processed_css = '';
2050  
2051          if ( empty( $css ) ) {
2052              return $processed_css;
2053          }
2054  
2055          // Split CSS nested rules.
2056          $parts = explode( '&', $css );
2057          foreach ( $parts as $part ) {
2058              if ( empty( $part ) ) {
2059                  continue;
2060              }
2061              $is_root_css = ( ! str_contains( $part, '{' ) );
2062              if ( $is_root_css ) {
2063                  // If the part doesn't contain braces, it applies to the root level.
2064                  $processed_css .= ':root :where(' . trim( $selector ) . '){' . trim( $part ) . '}';
2065              } else {
2066                  // If the part contains braces, it's a nested CSS rule.
2067                  $part = explode( '{', str_replace( '}', '', $part ) );
2068                  if ( count( $part ) !== 2 ) {
2069                      continue;
2070                  }
2071                  $nested_selector = $part[0];
2072                  $css_value       = $part[1];
2073  
2074                  /*
2075                   * Handle pseudo elements such as ::before, ::after etc. Regex will also
2076                   * capture any leading combinator such as >, +, or ~, as well as spaces.
2077                   * This allows pseudo elements as descendants e.g. `.parent ::before`.
2078                   */
2079                  $matches            = array();
2080                  $has_pseudo_element = preg_match( '/([>+~\s]*::[a-zA-Z-]+)/', $nested_selector, $matches );
2081                  $pseudo_part        = $has_pseudo_element ? $matches[1] : '';
2082                  $nested_selector    = $has_pseudo_element ? str_replace( $pseudo_part, '', $nested_selector ) : $nested_selector;
2083  
2084                  // Finalize selector and re-append pseudo element if required.
2085                  $part_selector  = str_starts_with( $nested_selector, ' ' )
2086                      ? static::scope_selector( $selector, $nested_selector )
2087                      : static::append_to_selector( $selector, $nested_selector );
2088                  $final_selector = ":root :where($part_selector)$pseudo_part";
2089  
2090                  $processed_css .= $final_selector . '{' . trim( $css_value ) . '}';
2091              }
2092          }
2093          return $processed_css;
2094      }
2095  
2096      /**
2097       * Returns the global styles custom CSS.
2098       *
2099       * @since 6.2.0
2100       * @deprecated 6.7.0 Use {@see 'get_stylesheet'} instead.
2101       *
2102       * @return string The global styles custom CSS.
2103       */
2104  	public function get_custom_css() {
2105          _deprecated_function( __METHOD__, '6.7.0', 'get_stylesheet' );
2106          // Add the global styles root CSS.
2107          $stylesheet = $this->theme_json['styles']['css'] ?? '';
2108  
2109          // Add the global styles block CSS.
2110          if ( isset( $this->theme_json['styles']['blocks'] ) ) {
2111              foreach ( $this->theme_json['styles']['blocks'] as $name => $node ) {
2112                  $custom_block_css = $this->theme_json['styles']['blocks'][ $name ]['css'] ?? null;
2113                  if ( $custom_block_css ) {
2114                      $selector    = static::$blocks_metadata[ $name ]['selector'];
2115                      $stylesheet .= $this->process_blocks_custom_css( $custom_block_css, $selector );
2116                  }
2117              }
2118          }
2119  
2120          return $stylesheet;
2121      }
2122  
2123      /**
2124       * Returns the page templates of the active theme.
2125       *
2126       * @since 5.9.0
2127       *
2128       * @return array
2129       */
2130  	public function get_custom_templates() {
2131          $custom_templates = array();
2132          if ( ! isset( $this->theme_json['customTemplates'] ) || ! is_array( $this->theme_json['customTemplates'] ) ) {
2133              return $custom_templates;
2134          }
2135  
2136          foreach ( $this->theme_json['customTemplates'] as $item ) {
2137              if ( isset( $item['name'] ) ) {
2138                  $custom_templates[ $item['name'] ] = array(
2139                      'title'     => $item['title'] ?? '',
2140                      'postTypes' => $item['postTypes'] ?? array( 'page' ),
2141                  );
2142              }
2143          }
2144          return $custom_templates;
2145      }
2146  
2147      /**
2148       * Returns the template part data of active theme.
2149       *
2150       * @since 5.9.0
2151       *
2152       * @return array
2153       */
2154  	public function get_template_parts() {
2155          $template_parts = array();
2156          if ( ! isset( $this->theme_json['templateParts'] ) || ! is_array( $this->theme_json['templateParts'] ) ) {
2157              return $template_parts;
2158          }
2159  
2160          foreach ( $this->theme_json['templateParts'] as $item ) {
2161              if ( isset( $item['name'] ) ) {
2162                  $template_parts[ $item['name'] ] = array(
2163                      'title' => $item['title'] ?? '',
2164                      'area'  => $item['area'] ?? '',
2165                  );
2166              }
2167          }
2168          return $template_parts;
2169      }
2170  
2171      /**
2172       * Converts each style section into a list of rulesets
2173       * containing the block styles to be appended to the stylesheet.
2174       *
2175       * See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax
2176       *
2177       * For each section this creates a new ruleset such as:
2178       *
2179       *   block-selector {
2180       *     style-property-one: value;
2181       *   }
2182       *
2183       * @since 5.8.0 As `get_block_styles()`.
2184       * @since 5.9.0 Renamed from `get_block_styles()` to `get_block_classes()`
2185       *              and no longer returns preset classes.
2186       *              Removed the `$setting_nodes` parameter.
2187       * @since 6.1.0 Moved most internal logic to `get_styles_for_block()`.
2188       *
2189       * @param array $style_nodes Nodes with styles.
2190       * @return string The new stylesheet.
2191       */
2192  	protected function get_block_classes( $style_nodes ) {
2193          $block_rules = '';
2194  
2195          foreach ( $style_nodes as $metadata ) {
2196              if ( null === $metadata['selector'] ) {
2197                  continue;
2198              }
2199              $block_rules .= static::get_styles_for_block( $metadata );
2200          }
2201  
2202          return $block_rules;
2203      }
2204  
2205      /**
2206       * Gets the CSS layout rules for a particular block from theme.json layout definitions.
2207       *
2208       * @since 6.1.0
2209       * @since 6.3.0 Reduced specificity for layout margin rules.
2210       * @since 6.5.1 Only output rules referencing content and wide sizes when values exist.
2211       * @since 6.5.3 Add types parameter to check if only base layout styles are needed.
2212       * @since 6.6.0 Updated layout style specificity to be compatible with overall 0-1-0 specificity in global styles.
2213       * @since 7.0.0 Replaced `$types` parameter with `$options` array; base layout styles controlled via `base_layout_styles` option.
2214       *
2215       * @param array $block_metadata Metadata about the block to get styles for.
2216       * @param array $options        Optional. An array of options for now used for internal purposes only.
2217       * @return string Layout styles for the block.
2218       */
2219  	protected function get_layout_styles( $block_metadata, $options = array() ) {
2220          $block_rules = '';
2221          $block_type  = null;
2222  
2223          // Skip outputting layout styles if explicitly disabled.
2224          if ( current_theme_supports( 'disable-layout-styles' ) ) {
2225              return $block_rules;
2226          }
2227  
2228          if ( isset( $block_metadata['name'] ) ) {
2229              $block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block_metadata['name'] );
2230              if ( ! block_has_support( $block_type, 'layout', false ) && ! block_has_support( $block_type, '__experimentalLayout', false ) ) {
2231                  return $block_rules;
2232              }
2233          }
2234  
2235          $selector                 = $block_metadata['selector'] ?? '';
2236          $has_block_gap_support    = isset( $this->theme_json['settings']['spacing']['blockGap'] );
2237          $has_fallback_gap_support = ! $has_block_gap_support; // This setting isn't useful yet: it exists as a placeholder for a future explicit fallback gap styles support.
2238          $node                     = $options['node'] ?? _wp_array_get( $this->theme_json, $block_metadata['path'], array() );
2239          $layout_definitions       = wp_get_layout_definitions();
2240          $layout_selector_pattern  = '/^[a-zA-Z0-9\-\.\,\ *+>:\(\)]*$/'; // Allow alphanumeric classnames, spaces, wildcard, sibling, child combinator and pseudo class selectors.
2241  
2242          /*
2243           * Gap styles will only be output if the theme has block gap support, or supports a fallback gap.
2244           * Default layout gap styles will be skipped for themes that do not explicitly opt-in to blockGap with a `true` or `false` value.
2245           */
2246          if ( $has_block_gap_support || $has_fallback_gap_support ) {
2247              $block_gap_value = null;
2248              // Use a fallback gap value if block gap support is not available.
2249              if ( ! $has_block_gap_support ) {
2250                  $block_gap_value = static::ROOT_BLOCK_SELECTOR === $selector ? '0.5em' : null;
2251                  if ( ! empty( $block_type ) ) {
2252                      $block_gap_value = $block_type->supports['spacing']['blockGap']['__experimentalDefault'] ?? null;
2253                  }
2254              } else {
2255                  $block_gap_value = static::get_property_value( $node, array( 'spacing', 'blockGap' ) );
2256              }
2257  
2258              // Support split row / column values and concatenate to a shorthand value.
2259              if ( is_array( $block_gap_value ) ) {
2260                  if ( isset( $block_gap_value['top'] ) && isset( $block_gap_value['left'] ) ) {
2261                      $gap_row         = static::get_property_value( $node, array( 'spacing', 'blockGap', 'top' ) );
2262                      $gap_column      = static::get_property_value( $node, array( 'spacing', 'blockGap', 'left' ) );
2263                      $block_gap_value = $gap_row === $gap_column ? $gap_row : $gap_row . ' ' . $gap_column;
2264                  } else {
2265                      // Skip outputting gap value if not all sides are provided.
2266                      $block_gap_value = null;
2267                  }
2268              }
2269  
2270              // If the block should have custom gap, add the gap styles.
2271              if ( null !== $block_gap_value && false !== $block_gap_value && '' !== $block_gap_value ) {
2272                  foreach ( $layout_definitions as $layout_definition_key => $layout_definition ) {
2273                      // Allow outputting fallback gap styles for flex and grid layout types when block gap support isn't available.
2274                      if ( ! $has_block_gap_support && 'flex' !== $layout_definition_key && 'grid' !== $layout_definition_key ) {
2275                          continue;
2276                      }
2277  
2278                      $class_name    = $layout_definition['className'] ?? false;
2279                      $spacing_rules = $layout_definition['spacingStyles'] ?? array();
2280  
2281                      if (
2282                          ! empty( $class_name ) &&
2283                          ! empty( $spacing_rules )
2284                      ) {
2285                          foreach ( $spacing_rules as $spacing_rule ) {
2286                              $declarations = array();
2287                              if (
2288                                  isset( $spacing_rule['selector'] ) &&
2289                                  preg_match( $layout_selector_pattern, $spacing_rule['selector'] ) &&
2290                                  ! empty( $spacing_rule['rules'] )
2291                              ) {
2292                                  // Iterate over each of the styling rules and substitute non-string values such as `null` with the real `blockGap` value.
2293                                  foreach ( $spacing_rule['rules'] as $css_property => $css_value ) {
2294                                      $current_css_value = is_string( $css_value ) ? $css_value : $block_gap_value;
2295                                      if ( static::is_safe_css_declaration( $css_property, $current_css_value ) ) {
2296                                          $declarations[] = array(
2297                                              'name'  => $css_property,
2298                                              'value' => $current_css_value,
2299                                          );
2300                                      }
2301                                  }
2302  
2303                                  if ( ! $has_block_gap_support ) {
2304                                      // For fallback gap styles, use lower specificity, to ensure styles do not unintentionally override theme styles.
2305                                      $format          = static::ROOT_BLOCK_SELECTOR === $selector ? ':where(.%2$s%3$s)' : ':where(%1$s.%2$s%3$s)';
2306                                      $layout_selector = sprintf(
2307                                          $format,
2308                                          $selector,
2309                                          $class_name,
2310                                          $spacing_rule['selector']
2311                                      );
2312                                  } else {
2313                                      $format          = static::ROOT_BLOCK_SELECTOR === $selector ? ':root :where(.%2$s)%3$s' : ':root :where(%1$s-%2$s)%3$s';
2314                                      $layout_selector = sprintf(
2315                                          $format,
2316                                          $selector,
2317                                          $class_name,
2318                                          $spacing_rule['selector']
2319                                      );
2320                                  }
2321                                  $block_rules .= static::to_ruleset( $layout_selector, $declarations );
2322                              }
2323                          }
2324                      }
2325                  }
2326              }
2327          }
2328  
2329          // Output base styles.
2330          if (
2331              static::ROOT_BLOCK_SELECTOR === $selector
2332          ) {
2333              $valid_display_modes = array( 'block', 'flex', 'grid' );
2334              foreach ( $layout_definitions as $layout_definition ) {
2335                  $class_name       = $layout_definition['className'] ?? false;
2336                  $base_style_rules = $layout_definition['baseStyles'] ?? array();
2337  
2338                  if (
2339                      ! empty( $class_name ) &&
2340                      is_array( $base_style_rules )
2341                  ) {
2342                      // Output display mode. This requires special handling as `display` is not exposed in `safe_style_css_filter`.
2343                      if (
2344                          ! empty( $layout_definition['displayMode'] ) &&
2345                          is_string( $layout_definition['displayMode'] ) &&
2346                          in_array( $layout_definition['displayMode'], $valid_display_modes, true )
2347                      ) {
2348                          $layout_selector = sprintf(
2349                              '%s .%s',
2350                              $selector,
2351                              $class_name
2352                          );
2353                          $block_rules    .= static::to_ruleset(
2354                              $layout_selector,
2355                              array(
2356                                  array(
2357                                      'name'  => 'display',
2358                                      'value' => $layout_definition['displayMode'],
2359                                  ),
2360                              )
2361                          );
2362                      }
2363  
2364                      foreach ( $base_style_rules as $base_style_rule ) {
2365                          $declarations = array();
2366  
2367                          // Skip outputting base styles for flow and constrained layout types when base_layout_styles is enabled.
2368                          // These themes don't use .wp-site-blocks wrapper, so these layout-specific alignment styles aren't needed.
2369                          if ( ! empty( $options['base_layout_styles'] ) && ( 'default' === $layout_definition['name'] || 'constrained' === $layout_definition['name'] ) ) {
2370                              continue;
2371                          }
2372  
2373                          if (
2374                              isset( $base_style_rule['selector'] ) &&
2375                              preg_match( $layout_selector_pattern, $base_style_rule['selector'] ) &&
2376                              ! empty( $base_style_rule['rules'] )
2377                          ) {
2378                              foreach ( $base_style_rule['rules'] as $css_property => $css_value ) {
2379                                  // Skip rules that reference content size or wide size if they are not defined in the theme.json.
2380                                  if (
2381                                      is_string( $css_value ) &&
2382                                      ( str_contains( $css_value, '--global--content-size' ) || str_contains( $css_value, '--global--wide-size' ) ) &&
2383                                      ! isset( $this->theme_json['settings']['layout']['contentSize'] ) &&
2384                                      ! isset( $this->theme_json['settings']['layout']['wideSize'] )
2385                                  ) {
2386                                      continue;
2387                                  }
2388  
2389                                  if ( static::is_safe_css_declaration( $css_property, $css_value ) ) {
2390                                      $declarations[] = array(
2391                                          'name'  => $css_property,
2392                                          'value' => $css_value,
2393                                      );
2394                                  }
2395                              }
2396  
2397                              $layout_selector = sprintf(
2398                                  '.%s%s',
2399                                  $class_name,
2400                                  $base_style_rule['selector']
2401                              );
2402                              $block_rules    .= static::to_ruleset( $layout_selector, $declarations );
2403                          }
2404                      }
2405                  }
2406              }
2407          }
2408  
2409          if ( ! empty( $options['media_query'] ) && ! empty( $block_rules ) ) {
2410              $block_rules = $options['media_query'] . '{' . $block_rules . '}';
2411          }
2412  
2413          return $block_rules;
2414      }
2415  
2416      /**
2417       * Creates new rulesets as classes for each preset value such as:
2418       *
2419       *   .has-value-color {
2420       *     color: value;
2421       *   }
2422       *
2423       *   .has-value-background-color {
2424       *     background-color: value;
2425       *   }
2426       *
2427       *   .has-value-font-size {
2428       *     font-size: value;
2429       *   }
2430       *
2431       *   .has-value-gradient-background {
2432       *     background: value;
2433       *   }
2434       *
2435       *   :where(p).has-value-gradient-background {
2436       *     background: value;
2437       *   }
2438       *
2439       * @since 5.9.0
2440       *
2441       * @param array    $setting_nodes Nodes with settings.
2442       * @param string[] $origins       List of origins to process presets from.
2443       * @return string The new stylesheet.
2444       */
2445  	protected function get_preset_classes( $setting_nodes, $origins ) {
2446          $preset_rules = '';
2447  
2448          foreach ( $setting_nodes as $metadata ) {
2449              if ( null === $metadata['selector'] ) {
2450                  continue;
2451              }
2452  
2453              $selector      = $metadata['selector'];
2454              $node          = _wp_array_get( $this->theme_json, $metadata['path'], array() );
2455              $preset_rules .= static::compute_preset_classes( $node, $selector, $origins );
2456          }
2457  
2458          return $preset_rules;
2459      }
2460  
2461      /**
2462       * Converts each styles section into a list of rulesets
2463       * to be appended to the stylesheet.
2464       * These rulesets contain all the css variables (custom variables and preset variables).
2465       *
2466       * See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax
2467       *
2468       * For each section this creates a new ruleset such as:
2469       *
2470       *     block-selector {
2471       *       --wp--preset--category--slug: value;
2472       *       --wp--custom--variable: value;
2473       *     }
2474       *
2475       * @since 5.8.0
2476       * @since 5.9.0 Added the `$origins` parameter.
2477       *
2478       * @param array    $nodes   Nodes with settings.
2479       * @param string[] $origins List of origins to process.
2480       * @return string The new stylesheet.
2481       */
2482  	protected function get_css_variables( $nodes, $origins ) {
2483          $stylesheet = '';
2484          foreach ( $nodes as $metadata ) {
2485              if ( null === $metadata['selector'] ) {
2486                  continue;
2487              }
2488  
2489              $selector          = $metadata['selector'];
2490              $feature_selectors = $metadata['selectors'] ?? array();
2491              $node              = _wp_array_get( $this->theme_json, $metadata['path'], array() );
2492  
2493              /*
2494               * Group preset declarations by selector. Blocks that define
2495               * feature-level selectors need their preset CSS variables
2496               * output under that feature selector instead of the block's
2497               * root selector.
2498               */
2499              $vars_by_selector              = array();
2500              $vars_by_selector[ $selector ] = array();
2501  
2502              foreach ( static::PRESETS_METADATA as $preset_metadata ) {
2503                  if ( empty( $preset_metadata['css_vars'] ) ) {
2504                      continue;
2505                  }
2506  
2507                  $values_by_slug = static::get_settings_values_by_slug( $node, $preset_metadata, $origins );
2508                  if ( empty( $values_by_slug ) ) {
2509                      continue;
2510                  }
2511  
2512                  $target = static::get_feature_selector( $feature_selectors, $preset_metadata['path'][0], $selector );
2513  
2514                  if ( ! isset( $vars_by_selector[ $target ] ) ) {
2515                      $vars_by_selector[ $target ] = array();
2516                  }
2517  
2518                  foreach ( $values_by_slug as $slug => $value ) {
2519                      $vars_by_selector[ $target ][] = array(
2520                          'name'  => static::replace_slug_in_string( $preset_metadata['css_vars'], $slug ),
2521                          'value' => $value,
2522                      );
2523                  }
2524              }
2525  
2526              // Theme vars always use the block's default selector.
2527              foreach ( static::compute_theme_vars( $node ) as $theme_var ) {
2528                  $vars_by_selector[ $selector ][] = $theme_var;
2529              }
2530  
2531              foreach ( $vars_by_selector as $rule_selector => $declarations ) {
2532                  $stylesheet .= static::to_ruleset( $rule_selector, $declarations );
2533              }
2534          }
2535  
2536          return $stylesheet;
2537      }
2538  
2539      /**
2540       * Returns the appropriate selector for a block support feature's
2541       * preset CSS variables.
2542       *
2543       * If the block defines a feature-level selector (as a string or an
2544       * object with a `root` key), that selector is returned. Otherwise,
2545       * the block's default selector is used.
2546       *
2547       * @since 7.1.0
2548       *
2549       * @param array<string, string|array<string, string>> $feature_selectors The block's feature selectors map.
2550       * @param string                                      $feature_key       The feature to look up (e.g. 'dimensions').
2551       * @param string                                      $default_selector  Fallback selector.
2552       * @return string The resolved selector.
2553       */
2554  	private static function get_feature_selector( array $feature_selectors, string $feature_key, string $default_selector ): string {
2555          if ( ! isset( $feature_selectors[ $feature_key ] ) ) {
2556              return $default_selector;
2557          }
2558  
2559          $feature = $feature_selectors[ $feature_key ];
2560  
2561          if ( is_string( $feature ) ) {
2562              return $feature;
2563          }
2564  
2565          if ( isset( $feature['root'] ) && is_string( $feature['root'] ) ) {
2566              return $feature['root'];
2567          }
2568  
2569          return $default_selector;
2570      }
2571  
2572      /**
2573       * Given a selector and a declaration list,
2574       * creates the corresponding ruleset.
2575       *
2576       * @since 5.8.0
2577       * @since 7.1.0 Skip declarations whose value is not a plain string (booleans, arrays, objects, etc.).
2578       *
2579       * @param string $selector     CSS selector.
2580       * @param array  $declarations List of declarations.
2581       * @return string The resulting CSS ruleset.
2582       */
2583  	protected static function to_ruleset( $selector, $declarations ) {
2584          if ( empty( $declarations ) ) {
2585              return '';
2586          }
2587  
2588          $declaration_block = array_reduce(
2589              $declarations,
2590              static function ( $carry, $element ) {
2591                  $value = $element['value'];
2592  
2593                  if ( is_numeric( $value ) ) {
2594                      $value = (string) $value;
2595                  }
2596  
2597                  if ( ! is_string( $value ) ) {
2598                      return $carry;
2599                  }
2600  
2601                  return $carry .= $element['name'] . ': ' . $value . ';';
2602              },
2603              ''
2604          );
2605  
2606          return $selector . '{' . $declaration_block . '}';
2607      }
2608  
2609      /**
2610       * Given a settings array, returns the generated rulesets
2611       * for the preset classes.
2612       *
2613       * @since 5.8.0
2614       * @since 5.9.0 Added the `$origins` parameter.
2615       * @since 6.6.0 Added check for root CSS properties selector.
2616       * @since 7.1.0 Wraps block-level preset classes in `:where()` to match root-level specificity.
2617       *
2618       * @param array    $settings Settings to process.
2619       * @param string   $selector Selector wrapping the classes.
2620       * @param string[] $origins  List of origins to process.
2621       * @return string The result of processing the presets.
2622       */
2623  	protected static function compute_preset_classes( $settings, $selector, $origins ) {
2624          if ( static::ROOT_BLOCK_SELECTOR === $selector || static::ROOT_CSS_PROPERTIES_SELECTOR === $selector ) {
2625              /*
2626               * Classes at the global level do not need any CSS prefixed,
2627               * and we don't want to increase its specificity.
2628               */
2629              $selector = '';
2630          }
2631  
2632          $stylesheet = '';
2633          foreach ( static::PRESETS_METADATA as $preset_metadata ) {
2634              if ( empty( $preset_metadata['classes'] ) ) {
2635                  continue;
2636              }
2637              $slugs = static::get_settings_slugs( $settings, $preset_metadata, $origins );
2638              foreach ( $preset_metadata['classes'] as $class => $property ) {
2639                  foreach ( $slugs as $slug ) {
2640                      $css_var    = static::replace_slug_in_string( $preset_metadata['css_vars'], $slug );
2641                      $class_name = static::replace_slug_in_string( $class, $slug );
2642  
2643                      /*
2644                       * $selector is often empty (root-level presets), in which case the
2645                       * bare class is used. For block-level presets the block selector is
2646                       * wrapped in `:where()` so the class keeps the same 0-1-0 specificity
2647                       * as a root-level preset. Without this, block-level palette rules
2648                       * (e.g. `p.has-x-color`) out-rank equally-important rules that also
2649                       * target the same property at 0-1-0, such as per-instance responsive
2650                       * state styles.
2651                       */
2652                      $new_selector = '' === $selector ? $class_name : ':where(' . $selector . ')' . $class_name;
2653                      $stylesheet  .= static::to_ruleset(
2654                          $new_selector,
2655                          array(
2656                              array(
2657                                  'name'  => $property,
2658                                  'value' => 'var(' . $css_var . ') !important',
2659                              ),
2660                          )
2661                      );
2662                  }
2663              }
2664          }
2665  
2666          return $stylesheet;
2667      }
2668  
2669      /**
2670       * Function that scopes a selector with another one. This works a bit like
2671       * SCSS nesting except the `&` operator isn't supported.
2672       *
2673       * <code>
2674       * $scope = '.a, .b .c';
2675       * $selector = '> .x, .y';
2676       * $merged = scope_selector( $scope, $selector );
2677       * // $merged is '.a > .x, .a .y, .b .c > .x, .b .c .y'
2678       * </code>
2679       *
2680       * @since 5.9.0
2681       * @since 6.6.0 Added early return if missing scope or selector.
2682       *
2683       * @param string $scope    Selector to scope to.
2684       * @param string $selector Original selector.
2685       * @return string Scoped selector.
2686       */
2687  	public static function scope_selector( $scope, $selector ) {
2688          if ( ! $scope || ! $selector ) {
2689              return $selector;
2690          }
2691  
2692          $scopes    = static::split_selector_list( $scope );
2693          $selectors = static::split_selector_list( $selector );
2694  
2695          $selectors_scoped = array();
2696          foreach ( $scopes as $outer ) {
2697              foreach ( $selectors as $inner ) {
2698                  if ( ! empty( $outer ) && ! empty( $inner ) ) {
2699                      $selectors_scoped[] = $outer . ' ' . $inner;
2700                  } elseif ( empty( $outer ) ) {
2701                      $selectors_scoped[] = $inner;
2702                  } elseif ( empty( $inner ) ) {
2703                      $selectors_scoped[] = $outer;
2704                  }
2705              }
2706          }
2707  
2708          $result = implode( ', ', $selectors_scoped );
2709          return $result;
2710      }
2711  
2712      /**
2713       * Scopes the selectors for a given style node.
2714       *
2715       * This includes the primary selector, i.e. `$node['selector']`, as well as any custom
2716       * selectors for features and subfeatures, e.g. `$node['selectors']['border']` etc.
2717       *
2718       * @since 6.6.0
2719       *
2720       * @param string $scope Selector to scope to.
2721       * @param array  $node  Style node with selectors to scope.
2722       * @return array Node with updated selectors.
2723       */
2724  	protected static function scope_style_node_selectors( $scope, $node ) {
2725          $node['selector'] = static::scope_selector( $scope, $node['selector'] );
2726  
2727          if ( empty( $node['selectors'] ) ) {
2728              return $node;
2729          }
2730  
2731          foreach ( $node['selectors'] as $feature => $selector ) {
2732              if ( is_string( $selector ) ) {
2733                  $node['selectors'][ $feature ] = static::scope_selector( $scope, $selector );
2734              }
2735              if ( is_array( $selector ) ) {
2736                  foreach ( $selector as $subfeature => $subfeature_selector ) {
2737                      $node['selectors'][ $feature ][ $subfeature ] = static::scope_selector( $scope, $subfeature_selector );
2738                  }
2739              }
2740          }
2741  
2742          return $node;
2743      }
2744  
2745      /**
2746       * Gets preset values keyed by slugs based on settings and metadata.
2747       *
2748       * <code>
2749       * $settings = array(
2750       *     'typography' => array(
2751       *         'fontFamilies' => array(
2752       *             array(
2753       *                 'slug'       => 'sansSerif',
2754       *                 'fontFamily' => '"Helvetica Neue", sans-serif',
2755       *             ),
2756       *             array(
2757       *                 'slug'   => 'serif',
2758       *                 'colors' => 'Georgia, serif',
2759       *             )
2760       *         ),
2761       *     ),
2762       * );
2763       * $meta = array(
2764       *    'path'      => array( 'typography', 'fontFamilies' ),
2765       *    'value_key' => 'fontFamily',
2766       * );
2767       * $values_by_slug = get_settings_values_by_slug();
2768       * // $values_by_slug === array(
2769       * //   'sans-serif' => '"Helvetica Neue", sans-serif',
2770       * //   'serif'      => 'Georgia, serif',
2771       * // );
2772       * </code>
2773       *
2774       * @since 5.9.0
2775       * @since 6.6.0 Passing $settings to the callbacks defined in static::PRESETS_METADATA.
2776       *
2777       * @param array    $settings        Settings to process.
2778       * @param array    $preset_metadata One of the PRESETS_METADATA values.
2779       * @param string[] $origins         List of origins to process.
2780       * @return array Array of presets where each key is a slug and each value is the preset value.
2781       */
2782  	protected static function get_settings_values_by_slug( $settings, $preset_metadata, $origins ) {
2783          $preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() );
2784  
2785          $result = array();
2786          foreach ( $origins as $origin ) {
2787              if ( ! isset( $preset_per_origin[ $origin ] ) ) {
2788                  continue;
2789              }
2790              foreach ( $preset_per_origin[ $origin ] as $preset ) {
2791                  $slug = _wp_to_kebab_case( $preset['slug'] );
2792  
2793                  $value = '';
2794                  if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) {
2795                      $value_key = $preset_metadata['value_key'];
2796                      $value     = $preset[ $value_key ];
2797                  } elseif (
2798                      isset( $preset_metadata['value_func'] ) &&
2799                      is_callable( $preset_metadata['value_func'] )
2800                  ) {
2801                      $value_func = $preset_metadata['value_func'];
2802                      $value      = call_user_func( $value_func, $preset, $settings );
2803                  } else {
2804                      // If we don't have a value, then don't add it to the result.
2805                      continue;
2806                  }
2807  
2808                  $result[ $slug ] = $value;
2809              }
2810          }
2811          return $result;
2812      }
2813  
2814      /**
2815       * Similar to get_settings_values_by_slug, but doesn't compute the value.
2816       *
2817       * @since 5.9.0
2818       *
2819       * @param array    $settings        Settings to process.
2820       * @param array    $preset_metadata One of the PRESETS_METADATA values.
2821       * @param string[] $origins         List of origins to process.
2822       * @return array Array of presets where the key and value are both the slug.
2823       */
2824  	protected static function get_settings_slugs( $settings, $preset_metadata, $origins = null ) {
2825          if ( null === $origins ) {
2826              $origins = static::VALID_ORIGINS;
2827          }
2828  
2829          $preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() );
2830  
2831          $result = array();
2832          foreach ( $origins as $origin ) {
2833              if ( ! isset( $preset_per_origin[ $origin ] ) ) {
2834                  continue;
2835              }
2836              foreach ( $preset_per_origin[ $origin ] as $preset ) {
2837                  $slug = _wp_to_kebab_case( $preset['slug'] );
2838  
2839                  // Use the array as a set so we don't get duplicates.
2840                  $result[ $slug ] = $slug;
2841              }
2842          }
2843          return $result;
2844      }
2845  
2846      /**
2847       * Transforms a slug into a CSS Custom Property.
2848       *
2849       * @since 5.9.0
2850       *
2851       * @param string $input String to replace.
2852       * @param string $slug  The slug value to use to generate the custom property.
2853       * @return string The CSS Custom Property. Something along the lines of `--wp--preset--color--black`.
2854       */
2855  	protected static function replace_slug_in_string( $input, $slug ) {
2856          return strtr( $input, array( '$slug' => $slug ) );
2857      }
2858  
2859      /**
2860       * Given the block settings, extracts the CSS Custom Properties
2861       * for the presets and adds them to the $declarations array
2862       * following the format:
2863       *
2864       *     array(
2865       *       'name'  => 'property_name',
2866       *       'value' => 'property_value,
2867       *     )
2868       *
2869       * @since 5.8.0
2870       * @since 5.9.0 Added the `$origins` parameter.
2871       *
2872       * @param array    $settings Settings to process.
2873       * @param string[] $origins  List of origins to process.
2874       * @return array The modified $declarations.
2875       */
2876  	protected static function compute_preset_vars( $settings, $origins ) {
2877          $declarations = array();
2878          foreach ( static::PRESETS_METADATA as $preset_metadata ) {
2879              if ( empty( $preset_metadata['css_vars'] ) ) {
2880                  continue;
2881              }
2882              $values_by_slug = static::get_settings_values_by_slug( $settings, $preset_metadata, $origins );
2883              foreach ( $values_by_slug as $slug => $value ) {
2884                  $declarations[] = array(
2885                      'name'  => static::replace_slug_in_string( $preset_metadata['css_vars'], $slug ),
2886                      'value' => $value,
2887                  );
2888              }
2889          }
2890  
2891          return $declarations;
2892      }
2893  
2894      /**
2895       * Given an array of settings, extracts the CSS Custom Properties
2896       * for the custom values and adds them to the $declarations
2897       * array following the format:
2898       *
2899       *     array(
2900       *       'name'  => 'property_name',
2901       *       'value' => 'property_value,
2902       *     )
2903       *
2904       * @since 5.8.0
2905       *
2906       * @param array $settings Settings to process.
2907       * @return array The modified $declarations.
2908       */
2909  	protected static function compute_theme_vars( $settings ) {
2910          $declarations  = array();
2911          $custom_values = $settings['custom'] ?? array();
2912          $css_vars      = static::flatten_tree( $custom_values );
2913          foreach ( $css_vars as $key => $value ) {
2914              $declarations[] = array(
2915                  'name'  => '--wp--custom--' . $key,
2916                  'value' => $value,
2917              );
2918          }
2919  
2920          return $declarations;
2921      }
2922  
2923      /**
2924       * Given a tree, it creates a flattened one
2925       * by merging the keys and binding the leaf values
2926       * to the new keys.
2927       *
2928       * It also transforms camelCase names into kebab-case
2929       * and substitutes '/' by '-'.
2930       *
2931       * This is thought to be useful to generate
2932       * CSS Custom Properties from a tree,
2933       * although there's nothing in the implementation
2934       * of this function that requires that format.
2935       *
2936       * For example, assuming the given prefix is '--wp'
2937       * and the token is '--', for this input tree:
2938       *
2939       *     {
2940       *       'some/property': 'value',
2941       *       'nestedProperty': {
2942       *         'sub-property': 'value'
2943       *       }
2944       *     }
2945       *
2946       * it'll return this output:
2947       *
2948       *     {
2949       *       '--wp--some-property': 'value',
2950       *       '--wp--nested-property--sub-property': 'value'
2951       *     }
2952       *
2953       * @since 5.8.0
2954       *
2955       * @param array  $tree   Input tree to process.
2956       * @param string $prefix Optional. Prefix to prepend to each variable. Default empty string.
2957       * @param string $token  Optional. Token to use between levels. Default '--'.
2958       * @return array The flattened tree.
2959       */
2960  	protected static function flatten_tree( $tree, $prefix = '', $token = '--' ) {
2961          $result = array();
2962          foreach ( $tree as $property => $value ) {
2963              $new_key = $prefix . str_replace(
2964                  '/',
2965                  '-',
2966                  strtolower( _wp_to_kebab_case( $property ) )
2967              );
2968  
2969              if ( is_array( $value ) ) {
2970                  $new_prefix        = $new_key . $token;
2971                  $flattened_subtree = static::flatten_tree( $value, $new_prefix, $token );
2972                  foreach ( $flattened_subtree as $subtree_key => $subtree_value ) {
2973                      $result[ $subtree_key ] = $subtree_value;
2974                  }
2975              } else {
2976                  $result[ $new_key ] = $value;
2977              }
2978          }
2979          return $result;
2980      }
2981  
2982      /**
2983       * Given a styles array, it extracts the style properties
2984       * and adds them to the $declarations array following the format:
2985       *
2986       *     array(
2987       *       'name'  => 'property_name',
2988       *       'value' => 'property_value',
2989       *     )
2990       *
2991       * @since 5.8.0
2992       * @since 5.9.0 Added the `$settings` and `$properties` parameters.
2993       * @since 6.1.0 Added `$theme_json`, `$selector`, and `$use_root_padding` parameters.
2994       * @since 6.5.0 Output a `min-height: unset` rule when `aspect-ratio` is set.
2995       * @since 6.6.0 Pass current theme JSON settings to wp_get_typography_font_size_value(), and process background properties.
2996       * @since 6.7.0 `ref` resolution of background properties, and assigning custom default values.
2997       *
2998       * @param array   $styles Styles to process.
2999       * @param array   $settings Theme settings.
3000       * @param array   $properties Properties metadata.
3001       * @param array   $theme_json Theme JSON array.
3002       * @param string  $selector The style block selector.
3003       * @param boolean $use_root_padding Whether to add custom properties at root level.
3004       * @return array Returns the modified $declarations.
3005       */
3006  	protected static function compute_style_properties( $styles, $settings = array(), $properties = null, $theme_json = null, $selector = null, $use_root_padding = null ) {
3007          if ( empty( $styles ) ) {
3008              return array();
3009          }
3010  
3011          if ( null === $properties ) {
3012              $properties = static::PROPERTIES_METADATA;
3013          }
3014          $declarations             = array();
3015          $root_variable_duplicates = array();
3016          $root_style_length        = strlen( '--wp--style--root--' );
3017  
3018          foreach ( $properties as $css_property => $value_path ) {
3019              if ( ! is_array( $value_path ) ) {
3020                  continue;
3021              }
3022  
3023              $is_root_style = str_starts_with( $css_property, '--wp--style--root--' );
3024              if ( $is_root_style && ( static::ROOT_BLOCK_SELECTOR !== $selector || ! $use_root_padding ) ) {
3025                  continue;
3026              }
3027  
3028              $value = static::get_property_value( $styles, $value_path, $theme_json );
3029  
3030              /*
3031               * Root-level padding styles don't currently support strings with CSS shorthand values.
3032               * This may change: https://github.com/WordPress/gutenberg/issues/40132.
3033               */
3034              if ( '--wp--style--root--padding' === $css_property && is_string( $value ) ) {
3035                  continue;
3036              }
3037  
3038              if ( $is_root_style && $use_root_padding ) {
3039                  $root_variable_duplicates[] = substr( $css_property, $root_style_length );
3040              }
3041  
3042              /*
3043               * Processes background image styles.
3044               * If the value is a URL, it will be converted to a CSS `url()` value.
3045               * For uploaded image (images with a database ID), apply size and position defaults,
3046               * equal to those applied in block supports in lib/background.php.
3047               */
3048              if ( 'background-image' === $css_property ) {
3049                  $background_image_input = array();
3050                  if ( ! empty( $value ) ) {
3051                      $background_image_input['backgroundImage'] = $value;
3052                  }
3053                  $gradient_value = $styles['background']['gradient'] ?? null;
3054                  if ( ! empty( $gradient_value ) ) {
3055                      $background_image_input['gradient'] = $gradient_value;
3056                  }
3057                  if ( ! empty( $background_image_input ) ) {
3058                      $background_styles = wp_style_engine_get_styles(
3059                          array( 'background' => $background_image_input )
3060                      );
3061                      $value             = $background_styles['declarations'][ $css_property ] ?? null;
3062                  }
3063              }
3064              if ( empty( $value ) && static::ROOT_BLOCK_SELECTOR !== $selector && ! empty( $styles['background']['backgroundImage']['id'] ) ) {
3065                  if ( 'background-size' === $css_property ) {
3066                      $value = 'cover';
3067                  }
3068                  // If the background size is set to `contain` and no position is set, set the position to `center`.
3069                  if ( 'background-position' === $css_property ) {
3070                      $background_size = $styles['background']['backgroundSize'] ?? null;
3071                      $value           = 'contain' === $background_size ? '50% 50%' : null;
3072                  }
3073              }
3074  
3075              // Skip if empty and not "0" or value represents array of longhand values.
3076              $has_missing_value = empty( $value ) && ! is_numeric( $value );
3077              if ( $has_missing_value || is_array( $value ) ) {
3078                  continue;
3079              }
3080  
3081              // Calculates fluid typography rules where available.
3082              if ( 'font-size' === $css_property ) {
3083                  /*
3084                   * wp_get_typography_font_size_value() will check
3085                   * if fluid typography has been activated and also
3086                   * whether the incoming value can be converted to a fluid value.
3087                   * Values that already have a clamp() function will not pass the test,
3088                   * and therefore the original $value will be returned.
3089                   * Pass the current theme_json settings to override any global settings.
3090                   */
3091                  $value = wp_get_typography_font_size_value( array( 'size' => $value ), $settings );
3092              }
3093  
3094              if ( 'aspect-ratio' === $css_property ) {
3095                  // For aspect ratio to work, other dimensions rules must be unset.
3096                  // This ensures that a fixed height does not override the aspect ratio.
3097                  $declarations[] = array(
3098                      'name'  => 'min-height',
3099                      'value' => 'unset',
3100                  );
3101              }
3102  
3103              $declarations[] = array(
3104                  'name'  => $css_property,
3105                  'value' => $value,
3106              );
3107          }
3108  
3109          // If a variable value is added to the root, the corresponding property should be removed.
3110          foreach ( $root_variable_duplicates as $duplicate ) {
3111              $discard = array_search( $duplicate, array_column( $declarations, 'name' ), true );
3112              if ( is_numeric( $discard ) ) {
3113                  array_splice( $declarations, $discard, 1 );
3114              }
3115          }
3116  
3117          return $declarations;
3118      }
3119  
3120      /**
3121       * Returns the style property for the given path.
3122       *
3123       * It also converts references to a path to the value
3124       * stored at that location, e.g.
3125       * { "ref": "style.color.background" } => "#fff".
3126       *
3127       * @since 5.8.0
3128       * @since 5.9.0 Added support for values of array type, which are returned as is.
3129       * @since 6.1.0 Added the `$theme_json` parameter.
3130       * @since 6.3.0 It no longer converts the internal format "var:preset|color|secondary"
3131       *              to the standard form "--wp--preset--color--secondary".
3132       *              This is already done by the sanitize method,
3133       *              so every property will be in the standard form.
3134       * @since 6.7.0 Added support for background image refs.
3135       *
3136       * @param array $styles Styles subtree.
3137       * @param array $path   Which property to process.
3138       * @param array $theme_json Theme JSON array.
3139       * @return string|array Style property value.
3140       */
3141  	protected static function get_property_value( $styles, $path, $theme_json = null ) {
3142          $value = _wp_array_get( $styles, $path, '' );
3143  
3144          if ( '' === $value || null === $value ) {
3145              // No need to process the value further.
3146              return '';
3147          }
3148  
3149          /*
3150           * This converts references to a path to the value at that path
3151           * where the value is an array with a "ref" key, pointing to a path.
3152           * For example: { "ref": "style.color.background" } => "#fff".
3153           * In the case of backgroundImage, if both a ref and a URL are present in the value,
3154           * the URL takes precedence and the ref is ignored.
3155           */
3156          if ( is_array( $value ) && isset( $value['ref'] ) ) {
3157              $value_path = explode( '.', $value['ref'] );
3158              $ref_value  = _wp_array_get( $theme_json, $value_path );
3159              // Background Image refs can refer to a string or an array containing a URL string.
3160              $ref_value_url = $ref_value['url'] ?? null;
3161              // Only use the ref value if we find anything.
3162              if ( ! empty( $ref_value ) && ( is_string( $ref_value ) || is_string( $ref_value_url ) ) ) {
3163                  $value = $ref_value;
3164              }
3165  
3166              if ( is_array( $ref_value ) && isset( $ref_value['ref'] ) ) {
3167                  $path_string      = json_encode( $path );
3168                  $ref_value_string = json_encode( $ref_value );
3169                  _doing_it_wrong(
3170                      'get_property_value',
3171                      sprintf(
3172                          /* translators: 1: theme.json, 2: Value name, 3: Value path, 4: Another value name. */
3173                          __( 'Your %1$s file uses a dynamic value (%2$s) for the path at %3$s. However, the value at %3$s is also a dynamic value (pointing to %4$s) and pointing to another dynamic value is not supported. Please update %3$s to point directly to %4$s.' ),
3174                          'theme.json',
3175                          $ref_value_string,
3176                          $path_string,
3177                          $ref_value['ref']
3178                      ),
3179                      '6.1.0'
3180                  );
3181              }
3182          }
3183  
3184          return $value;
3185      }
3186  
3187      /**
3188       * Builds metadata for the setting nodes, which returns in the form of:
3189       *
3190       *     [
3191       *       [
3192       *         'path'     => ['path', 'to', 'some', 'node' ],
3193       *         'selector' => 'CSS selector for some node'
3194       *       ],
3195       *       [
3196       *         'path'     => [ 'path', 'to', 'other', 'node' ],
3197       *         'selector' => 'CSS selector for other node'
3198       *       ],
3199       *     ]
3200       *
3201       * @since 5.8.0
3202       *
3203       * @param array $theme_json The tree to extract setting nodes from.
3204       * @param array $selectors  List of selectors per block.
3205       * @return array An array of setting nodes metadata.
3206       */
3207  	protected static function get_setting_nodes( $theme_json, $selectors = array() ) {
3208          $nodes = array();
3209          if ( ! isset( $theme_json['settings'] ) ) {
3210              return $nodes;
3211          }
3212  
3213          // Top-level.
3214          $nodes[] = array(
3215              'path'     => array( 'settings' ),
3216              'selector' => static::ROOT_CSS_PROPERTIES_SELECTOR,
3217          );
3218  
3219          // Calculate paths for blocks.
3220          if ( ! isset( $theme_json['settings']['blocks'] ) ) {
3221              return $nodes;
3222          }
3223  
3224          foreach ( $theme_json['settings']['blocks'] as $name => $node ) {
3225              $selector = null;
3226              if ( isset( $selectors[ $name ]['selector'] ) ) {
3227                  $selector = $selectors[ $name ]['selector'];
3228              }
3229  
3230              $nodes[] = array(
3231                  'path'      => array( 'settings', 'blocks', $name ),
3232                  'selector'  => $selector,
3233                  'selectors' => $selectors[ $name ]['selectors'] ?? array(),
3234              );
3235          }
3236  
3237          return $nodes;
3238      }
3239  
3240      /**
3241       * Builds metadata for the style nodes, which returns in the form of:
3242       *
3243       *     [
3244       *       [
3245       *         'path'     => [ 'path', 'to', 'some', 'node' ],
3246       *         'selector' => 'CSS selector for some node',
3247       *         'duotone'  => 'CSS selector for duotone for some node'
3248       *       ],
3249       *       [
3250       *         'path'     => ['path', 'to', 'other', 'node' ],
3251       *         'selector' => 'CSS selector for other node',
3252       *         'duotone'  => null
3253       *       ],
3254       *     ]
3255       *
3256       * @since 5.8.0
3257       * @since 6.6.0 Added options array for modifying generated nodes.
3258       *
3259       * @param array $theme_json The tree to extract style nodes from.
3260       * @param array $selectors  List of selectors per block.
3261       * @param array $options {
3262       *     Optional. An array of options for now used for internal purposes only (may change without notice).
3263       *
3264       *     @type bool $include_block_style_variations Includes style nodes for block style variations. Default false.
3265       * }
3266       * @return array An array of style nodes metadata.
3267       */
3268  	protected static function get_style_nodes( $theme_json, $selectors = array(), $options = array() ) {
3269          $nodes = array();
3270          if ( ! isset( $theme_json['styles'] ) ) {
3271              return $nodes;
3272          }
3273  
3274          // Top-level.
3275          $nodes[] = array(
3276              'path'     => array( 'styles' ),
3277              'selector' => static::ROOT_BLOCK_SELECTOR,
3278          );
3279  
3280          if ( isset( $theme_json['styles']['elements'] ) ) {
3281              foreach ( self::ELEMENTS as $element => $selector ) {
3282                  if ( ! isset( $theme_json['styles']['elements'][ $element ] ) ) {
3283                      continue;
3284                  }
3285                  $nodes[] = array(
3286                      'path'     => array( 'styles', 'elements', $element ),
3287                      'selector' => static::ELEMENTS[ $element ],
3288                  );
3289  
3290                  // Handle any pseudo selectors for the element.
3291                  if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) {
3292                      foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
3293  
3294                          if ( isset( $theme_json['styles']['elements'][ $element ][ $pseudo_selector ] ) ) {
3295                              $nodes[] = array(
3296                                  'path'     => array( 'styles', 'elements', $element ),
3297                                  'selector' => static::append_to_selector( static::ELEMENTS[ $element ], $pseudo_selector ),
3298                              );
3299                          }
3300                      }
3301                  }
3302              }
3303          }
3304  
3305          // Blocks.
3306          if ( ! isset( $theme_json['styles']['blocks'] ) ) {
3307              return $nodes;
3308          }
3309  
3310          $block_nodes = static::get_block_nodes( $theme_json, $selectors, $options );
3311          foreach ( $block_nodes as $block_node ) {
3312              $nodes[] = $block_node;
3313          }
3314  
3315          /**
3316           * Filters the list of style nodes with metadata.
3317           *
3318           * This allows for things like loading block CSS independently.
3319           *
3320           * @since 6.1.0
3321           *
3322           * @param array $nodes Style nodes with metadata.
3323           */
3324          return apply_filters( 'wp_theme_json_get_style_nodes', $nodes );
3325      }
3326  
3327      /**
3328       * A public helper to get the block nodes from a theme.json file.
3329       *
3330       * @since 6.1.0
3331       *
3332       * @return array The block nodes in theme.json.
3333       */
3334  	public function get_styles_block_nodes() {
3335          return static::get_block_nodes( $this->theme_json );
3336      }
3337  
3338      /**
3339       * Returns a filtered declarations array if there is a separator block with only a background
3340       * style defined in theme.json by adding a color attribute to reflect the changes in the front.
3341       *
3342       * @since 6.1.1
3343       *
3344       * @param array $declarations List of declarations.
3345       * @return array $declarations List of declarations filtered.
3346       */
3347  	private static function update_separator_declarations( $declarations ) {
3348          $background_color     = '';
3349          $border_color_matches = false;
3350          $text_color_matches   = false;
3351  
3352          foreach ( $declarations as $declaration ) {
3353              if ( 'background-color' === $declaration['name'] && ! $background_color && isset( $declaration['value'] ) ) {
3354                  $background_color = $declaration['value'];
3355              } elseif ( 'border-color' === $declaration['name'] ) {
3356                  $border_color_matches = true;
3357              } elseif ( 'color' === $declaration['name'] ) {
3358                  $text_color_matches = true;
3359              }
3360  
3361              if ( $background_color && $border_color_matches && $text_color_matches ) {
3362                  break;
3363              }
3364          }
3365  
3366          if ( $background_color && ! $border_color_matches && ! $text_color_matches ) {
3367              $declarations[] = array(
3368                  'name'  => 'color',
3369                  'value' => $background_color,
3370              );
3371          }
3372  
3373          return $declarations;
3374      }
3375  
3376      /**
3377       * Updates the text indent selector for paragraph blocks based on the textIndent setting.
3378       *
3379       * The textIndent setting can be 'subsequent' (default), 'all', or false.
3380       * When set to 'all', the selector should be '.wp-block-paragraph' instead of
3381       * '.wp-block-paragraph + .wp-block-paragraph' to apply indent to all paragraphs.
3382       *
3383       * @since 7.0.0
3384       *
3385       * @param array  $feature_declarations The feature declarations keyed by selector.
3386       * @param array  $settings             The theme.json settings.
3387       * @param string $block_name           The block name being processed.
3388       * @return array The updated feature declarations.
3389       */
3390  	private static function update_paragraph_text_indent_selector( $feature_declarations, $settings, $block_name ) {
3391          if ( 'core/paragraph' !== $block_name ) {
3392              return $feature_declarations;
3393          }
3394  
3395          // Check block-level settings first, then fall back to global settings.
3396          $block_settings      = $settings['blocks']['core/paragraph'] ?? null;
3397          $text_indent_setting = $block_settings['typography']['textIndent']
3398              ?? $settings['typography']['textIndent']
3399              ?? 'subsequent';
3400  
3401          if ( 'all' !== $text_indent_setting ) {
3402              return $feature_declarations;
3403          }
3404  
3405          // Look for the text indent selector and replace it.
3406          $old_selector = '.wp-block-paragraph + .wp-block-paragraph';
3407          $new_selector = '.wp-block-paragraph';
3408  
3409          if ( isset( $feature_declarations[ $old_selector ] ) ) {
3410              $declarations = $feature_declarations[ $old_selector ];
3411              unset( $feature_declarations[ $old_selector ] );
3412              $feature_declarations[ $new_selector ] = $declarations;
3413          }
3414  
3415          return $feature_declarations;
3416      }
3417  
3418      /**
3419       * Updates button width declarations to use a calc() formula for percentage values.
3420       *
3421       * When a percentage width is set on the Button block via Global Styles, the
3422       * resulting CSS needs to account for block gap spacing so that buttons tile
3423       * correctly on a row (e.g. 4 buttons at 25% width all fit on one row).
3424       *
3425       * This mirrors the dynamic calc() formula applied at the block instance level
3426       * in the button block's stylesheet (style.scss).
3427       *
3428       * @since 7.1.0
3429       *
3430       * @param array $feature_declarations The feature declarations keyed by selector.
3431       * @param array $settings             The theme.json settings.
3432       * @return array The updated feature declarations.
3433       */
3434  	private static function update_button_width_declarations( $feature_declarations, $settings ) {
3435          if ( ! isset( $feature_declarations['.wp-block-button'] ) ) {
3436              return $feature_declarations;
3437          }
3438  
3439          foreach ( $feature_declarations['.wp-block-button'] as &$declaration ) {
3440              if ( 'width' !== $declaration['name'] || ! isset( $declaration['value'] ) ) {
3441                  continue;
3442              }
3443  
3444              $value      = $declaration['value'];
3445              $percentage = null;
3446  
3447              // Case 1: Direct percentage value e.g. "25%".
3448              if ( is_string( $value ) && str_ends_with( $value, '%' ) ) {
3449                  $percentage = (float) $value;
3450              }
3451  
3452              // Case 2: Preset CSS var e.g. "var(--wp--preset--dimension--50)".
3453              if ( null === $percentage && is_string( $value ) && str_starts_with( $value, 'var(--wp--preset--dimension--' ) ) {
3454                  // Extract the slug from the var name.
3455                  $slug = substr( $value, strlen( 'var(--wp--preset--dimension--' ), -1 );
3456  
3457                  /*
3458                   * Look up the preset size across all origins.
3459                   * Check block-level settings first (core/button), then top-level settings.
3460                   */
3461                  $dimension_sizes = ( $settings['blocks']['core/button']['dimensions']['dimensionSizes'] ?? array() )
3462                      + ( $settings['dimensions']['dimensionSizes'] ?? array() );
3463                  foreach ( $dimension_sizes as $origin_sizes ) {
3464                      if ( ! is_array( $origin_sizes ) ) {
3465                          continue;
3466                      }
3467                      foreach ( $origin_sizes as $preset ) {
3468                          if ( isset( $preset['slug'] ) && $slug === $preset['slug'] && isset( $preset['size'] ) ) {
3469                              $size = $preset['size'];
3470                              if ( is_string( $size ) && str_ends_with( $size, '%' ) ) {
3471                                  $percentage = (float) $size;
3472                              }
3473                              break 2;
3474                          }
3475                      }
3476                  }
3477              }
3478  
3479              if ( null === $percentage ) {
3480                  continue;
3481              }
3482  
3483              /*
3484               * Apply the same calc() formula as the block instance level (style.scss).
3485               * The numeric percentage value is used as a unitless number:
3486               * - Multiplied by 1% to get the percentage width.
3487               * - Divided by 100 to calculate the gap adjustment proportion.
3488               */
3489              $declaration['value'] = sprintf(
3490                  'calc(%s * 1%% - (var(--wp--style--block-gap, 0.5em) * (1 - %s / 100)))',
3491                  $percentage,
3492                  $percentage
3493              );
3494          }
3495          unset( $declaration );
3496  
3497          return $feature_declarations;
3498      }
3499  
3500      /**
3501       * An internal method to get the block nodes from a theme.json file.
3502       *
3503       * @since 6.1.0
3504       * @since 6.3.0 Refactored and stabilized selectors API.
3505       * @since 6.6.0 Added optional selectors and options for generating block nodes.
3506       * @since 6.7.0 Added $include_node_paths_only option.
3507       * @since 7.1.0 Added responsive block nodes for breakpoint-based styles.
3508       *
3509       * @param array $theme_json The theme.json converted to an array.
3510       * @param array $selectors  Optional list of selectors per block.
3511       * @param array $options {
3512       *     Optional. An array of options for now used for internal purposes only (may change without notice).
3513       *
3514       *     @type bool $include_block_style_variations Include nodes for block style variations. Default false.
3515       *     @type bool $include_node_paths_only        Return only block nodes node paths. Default false.
3516       * }
3517       * @return array The block nodes in theme.json.
3518       */
3519  	private static function get_block_nodes( $theme_json, $selectors = array(), $options = array() ) {
3520          $nodes = array();
3521  
3522          if ( ! isset( $theme_json['styles']['blocks'] ) ) {
3523              return $nodes;
3524          }
3525  
3526          $include_variations       = $options['include_block_style_variations'] ?? false;
3527          $include_node_paths_only  = $options['include_node_paths_only'] ?? false;
3528          $responsive_media_queries = static::get_viewport_media_queries( $theme_json['settings']['viewport'] ?? null );
3529  
3530          // If only node paths are to be returned, skip selector assignment.
3531          if ( ! $include_node_paths_only ) {
3532              $selectors = empty( $selectors ) ? static::get_blocks_metadata() : $selectors;
3533          }
3534  
3535          foreach ( $theme_json['styles']['blocks'] as $name => $node ) {
3536              $node_path = array( 'styles', 'blocks', $name );
3537              if ( $include_node_paths_only ) {
3538                  $variation_paths = array();
3539                  if ( $include_variations && isset( $node['variations'] ) ) {
3540                      foreach ( $node['variations'] as $variation => $variation_node ) {
3541                          $variation_paths[] = array(
3542                              'path' => array( 'styles', 'blocks', $name, 'variations', $variation ),
3543                          );
3544                      }
3545                  }
3546                  $node = array(
3547                      'path' => $node_path,
3548                  );
3549                  if ( ! empty( $variation_paths ) ) {
3550                      $node['variations'] = $variation_paths;
3551                  }
3552                  $nodes[] = $node;
3553              } else {
3554                  $selector = null;
3555                  if ( isset( $selectors[ $name ]['selector'] ) ) {
3556                      $selector = $selectors[ $name ]['selector'];
3557                  }
3558  
3559                  $duotone_selector = null;
3560                  if ( isset( $selectors[ $name ]['duotone'] ) ) {
3561                      $duotone_selector = $selectors[ $name ]['duotone'];
3562                  }
3563  
3564                  $feature_selectors = null;
3565                  if ( isset( $selectors[ $name ]['selectors'] ) ) {
3566                      $feature_selectors = $selectors[ $name ]['selectors'];
3567                  }
3568  
3569                  $variation_selectors = array();
3570  
3571                  if ( $include_variations && isset( $node['variations'] ) ) {
3572                      foreach ( $node['variations'] as $variation => $node ) {
3573                          $variation_selectors[] = array(
3574                              'name'     => $variation,
3575                              'path'     => array( 'styles', 'blocks', $name, 'variations', $variation ),
3576                              'selector' => $selectors[ $name ]['styleVariations'][ $variation ],
3577                          );
3578                      }
3579                  }
3580  
3581                  $nodes[] = array(
3582                      'name'       => $name,
3583                      'path'       => $node_path,
3584                      'selector'   => $selector,
3585                      'selectors'  => $feature_selectors,
3586                      'elements'   => $selectors[ $name ]['elements'] ?? array(),
3587                      'duotone'    => $duotone_selector,
3588                      'variations' => $variation_selectors,
3589                      'css'        => $selector,
3590                  );
3591  
3592                  // Responsive block nodes: emit one node per breakpoint that has styles.
3593                  // These are rendered immediately after the base block node so that
3594                  // the cascade order is: .block{} → @media{.block{}}
3595                  foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3596                      if ( isset( $theme_json['styles']['blocks'][ $name ][ $breakpoint ] ) ) {
3597                          $nodes[] = array(
3598                              'name'        => $name,
3599                              'path'        => array( 'styles', 'blocks', $name, $breakpoint ),
3600                              'media_query' => $responsive_media_queries[ $breakpoint ],
3601                              'selector'    => $selector,
3602                              'selectors'   => $feature_selectors,
3603                              'elements'    => $selectors[ $name ]['elements'] ?? array(),
3604                              'variations'  => $variation_selectors,
3605                              'css'         => $selector,
3606                          );
3607                      }
3608                  }
3609  
3610                  // Handle any pseudo selectors for the block.
3611                  if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $name ] ) ) {
3612                      foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $name ] as $pseudo_selector ) {
3613                          $has_pseudo            = isset( $theme_json['styles']['blocks'][ $name ][ $pseudo_selector ] );
3614                          $has_responsive_pseudo = false;
3615                          foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3616                              if ( isset( $theme_json['styles']['blocks'][ $name ][ $breakpoint ][ $pseudo_selector ] ) ) {
3617                                  $has_responsive_pseudo = true;
3618                                  break;
3619                              }
3620                          }
3621  
3622                          if ( ! $has_pseudo && ! $has_responsive_pseudo ) {
3623                              continue;
3624                          }
3625  
3626                          /*
3627                           * Append the pseudo-selector to each feature selector so that
3628                           * get_feature_declarations_for_node generates CSS scoped to the
3629                           * pseudo-state (e.g. '.wp-block-button:hover') rather than the
3630                           * default state (e.g. '.wp-block-button').
3631                           */
3632                          $pseudo_feature_selectors = array();
3633                          foreach ( $feature_selectors ?? array() as $feature => $feature_selector ) {
3634                              if ( is_array( $feature_selector ) ) {
3635                                  $pseudo_feature_selectors[ $feature ] = array();
3636                                  foreach ( $feature_selector as $subfeature => $subfeature_selector ) {
3637                                      $pseudo_feature_selectors[ $feature ][ $subfeature ] = static::append_to_selector( $subfeature_selector, $pseudo_selector );
3638                                  }
3639                              } else {
3640                                  $pseudo_feature_selectors[ $feature ] = static::append_to_selector( $feature_selector, $pseudo_selector );
3641                              }
3642                          }
3643  
3644                          if ( $has_pseudo ) {
3645                              $nodes[] = array(
3646                                  'name'       => $name,
3647                                  'path'       => array( 'styles', 'blocks', $name, $pseudo_selector ),
3648                                  'selector'   => static::append_to_selector( $selector, $pseudo_selector ),
3649                                  'selectors'  => $pseudo_feature_selectors,
3650                                  'elements'   => $selectors[ $name ]['elements'] ?? array(),
3651                                  'duotone'    => $duotone_selector,
3652                                  'variations' => $variation_selectors,
3653                                  'css'        => static::append_to_selector( $selector, $pseudo_selector ),
3654                              );
3655                          }
3656  
3657                          // Responsive pseudo nodes: emit one node per breakpoint that has
3658                          // this pseudo state, immediately after the default pseudo node.
3659                          // Cascade order: .block:hover{} → @media{.block:hover{}}
3660                          foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3661                              if ( isset( $theme_json['styles']['blocks'][ $name ][ $breakpoint ][ $pseudo_selector ] ) ) {
3662                                  $nodes[] = array(
3663                                      'name'        => $name,
3664                                      'path'        => array( 'styles', 'blocks', $name, $breakpoint, $pseudo_selector ),
3665                                      'media_query' => $responsive_media_queries[ $breakpoint ],
3666                                      'selector'    => static::append_to_selector( $selector, $pseudo_selector ),
3667                                      'selectors'   => $pseudo_feature_selectors,
3668                                      'elements'    => $selectors[ $name ]['elements'] ?? array(),
3669                                      'variations'  => $variation_selectors,
3670                                      'css'         => static::append_to_selector( $selector, $pseudo_selector ),
3671                                  );
3672                              }
3673                          }
3674                      }
3675                  }
3676  
3677                  // Handle custom states (e.g. '-current' for navigation).
3678                  if ( isset( static::VALID_BLOCK_CUSTOM_STATES[ $name ] ) ) {
3679                      foreach ( static::VALID_BLOCK_CUSTOM_STATES[ $name ] as $custom_state ) {
3680                          if (
3681                              isset( $theme_json['styles']['blocks'][ $name ][ $custom_state ] ) &&
3682                              isset( $selectors[ $name ]['states'][ $custom_state ] )
3683                          ) {
3684                              $custom_css_selector = $selectors[ $name ]['states'][ $custom_state ];
3685                              $nodes[]             = array(
3686                                  'name'       => $name,
3687                                  'path'       => array( 'styles', 'blocks', $name, $custom_state ),
3688                                  'selector'   => $custom_css_selector,
3689                                  'selectors'  => $feature_selectors,
3690                                  'elements'   => $selectors[ $name ]['elements'] ?? array(),
3691                                  'duotone'    => $duotone_selector,
3692                                  'variations' => $variation_selectors,
3693                                  'css'        => $custom_css_selector,
3694                              );
3695  
3696                              // Sub-pseudo-selectors within the custom state.
3697                              if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $name ] ) ) {
3698                                  foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $name ] as $pseudo ) {
3699                                      if ( isset( $theme_json['styles']['blocks'][ $name ][ $custom_state ][ $pseudo ] ) ) {
3700                                          $compound_css_selector = static::append_to_selector( $custom_css_selector, $pseudo );
3701                                          $nodes[]               = array(
3702                                              'name'       => $name,
3703                                              'path'       => array( 'styles', 'blocks', $name, $custom_state, $pseudo ),
3704                                              'selector'   => $compound_css_selector,
3705                                              'selectors'  => $feature_selectors,
3706                                              'elements'   => $selectors[ $name ]['elements'] ?? array(),
3707                                              'duotone'    => $duotone_selector,
3708                                              'variations' => $variation_selectors,
3709                                              'css'        => $compound_css_selector,
3710                                          );
3711                                      }
3712                                  }
3713                              }
3714                          }
3715                      }
3716                  }
3717              }
3718              /*
3719               * Elements can be styled outside any breakpoint, inside one, or both,
3720               * so collect the names from all of those places before looping. An
3721               * element styled only inside a breakpoint still needs a node.
3722               */
3723              $block_node    = $theme_json['styles']['blocks'][ $name ] ?? array();
3724              $element_names = array_keys( $block_node['elements'] ?? array() );
3725              foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3726                  $element_names = array_merge(
3727                      $element_names,
3728                      array_keys( $block_node[ $breakpoint ]['elements'] ?? array() )
3729                  );
3730              }
3731              $element_names = array_unique( $element_names );
3732  
3733              if ( ! empty( $element_names ) ) {
3734                  foreach ( $element_names as $element ) {
3735                      $element_path = array( 'styles', 'blocks', $name, 'elements', $element );
3736                      if ( $include_node_paths_only ) {
3737                          if ( isset( $block_node['elements'][ $element ] ) ) {
3738                              $nodes[] = array(
3739                                  'path' => $element_path,
3740                              );
3741                          }
3742                          continue;
3743                      }
3744  
3745                      if ( ! isset( $selectors[ $name ]['elements'][ $element ] ) ) {
3746                          continue;
3747                      }
3748  
3749                      $element_selector = $selectors[ $name ]['elements'][ $element ];
3750  
3751                      if ( isset( $block_node['elements'][ $element ] ) ) {
3752                          $nodes[] = array(
3753                              'path'     => $element_path,
3754                              'selector' => $element_selector,
3755                          );
3756                      }
3757  
3758                      // Responsive element nodes: one node per breakpoint that has
3759                      // styles for this element. Cascade: a{} → @media{a{}}
3760                      foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3761                          if ( isset( $theme_json['styles']['blocks'][ $name ][ $breakpoint ]['elements'][ $element ] ) ) {
3762                              $nodes[] = array(
3763                                  'path'        => array( 'styles', 'blocks', $name, $breakpoint, 'elements', $element ),
3764                                  'selector'    => $element_selector,
3765                                  'media_query' => $responsive_media_queries[ $breakpoint ],
3766                              );
3767                          }
3768                      }
3769  
3770                      // Handle any pseudo selectors for the element.
3771                      if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) {
3772                          foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
3773                              // Emit the default pseudo node only when the default state styles
3774                              // the pseudo. Otherwise get_styles_for_block() falls back to the
3775                              // element's base styles, outputting a rule the theme never defined.
3776                              if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'][ $element ][ $pseudo_selector ] ) ) {
3777                                  $nodes[] = array(
3778                                      'path'     => array( 'styles', 'blocks', $name, 'elements', $element ),
3779                                      'selector' => static::append_to_selector( $element_selector, $pseudo_selector ),
3780                                  );
3781                              }
3782  
3783                              // Responsive element pseudo nodes: one node per breakpoint
3784                              // that has this pseudo state for this element.
3785                              // Cascade: a:hover{} → @media{a:hover{}}
3786                              foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3787                                  if ( isset( $theme_json['styles']['blocks'][ $name ][ $breakpoint ]['elements'][ $element ][ $pseudo_selector ] ) ) {
3788                                      $nodes[] = array(
3789                                          'path'        => array( 'styles', 'blocks', $name, $breakpoint, 'elements', $element ),
3790                                          'selector'    => static::append_to_selector( $element_selector, $pseudo_selector ),
3791                                          'media_query' => $responsive_media_queries[ $breakpoint ],
3792                                      );
3793                                  }
3794                              }
3795                          }
3796                      }
3797                  }
3798              }
3799          }
3800  
3801          return $nodes;
3802      }
3803  
3804      /**
3805       * Gets the CSS rules for a particular block from theme.json.
3806       *
3807       * @since 6.1.0
3808       * @since 6.6.0 Setting a min-height of HTML when root styles have a background gradient or image.
3809       *              Updated general global styles specificity to 0-1-0.
3810       *              Fixed custom CSS output in block style variations.
3811       *
3812       * @param array $block_metadata Metadata about the block to get styles for.
3813       * @return string Styles for the block.
3814       */
3815  	public function get_styles_for_block( $block_metadata ) {
3816          $node                     = _wp_array_get( $this->theme_json, $block_metadata['path'], array() );
3817          $use_root_padding         = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments'];
3818          $selector                 = $block_metadata['selector'];
3819          $settings                 = $this->theme_json['settings'] ?? array();
3820          $feature_declarations     = static::get_feature_declarations_for_node( $block_metadata, $node );
3821          $is_root_selector         = static::ROOT_BLOCK_SELECTOR === $selector;
3822          $media_query              = $block_metadata['media_query'] ?? null;
3823          $responsive_media_queries = static::get_viewport_media_queries( $settings['viewport'] ?? null );
3824  
3825          // Update text indent selector for paragraph blocks based on the textIndent setting.
3826          $block_name           = $block_metadata['name'] ?? null;
3827          $feature_declarations = static::update_paragraph_text_indent_selector( $feature_declarations, $settings, $block_name );
3828          $block_elements       = $block_metadata['elements'] ?? array();
3829  
3830          // Update button width declarations for percentage values to use calc() with block gap.
3831          $feature_declarations = static::update_button_width_declarations( $feature_declarations, $settings );
3832  
3833          // If there are style variations, generate the declarations for them, including any feature selectors the block may have.
3834          $style_variation_declarations          = array();
3835          $style_variation_custom_css            = array();
3836          $style_variation_responsive_css        = array();
3837          $style_variation_responsive_pseudo_css = array();
3838          $style_variation_layout_metadata       = array();
3839          if ( ! $media_query && ! empty( $block_metadata['variations'] ) ) {
3840              foreach ( $block_metadata['variations'] as $style_variation ) {
3841                  $style_variation_node = _wp_array_get( $this->theme_json, $style_variation['path'], array() );
3842  
3843                  // Generate any feature/subfeature style declarations for the current style variation.
3844                  $variation_declarations = static::get_feature_declarations_for_node( $block_metadata, $style_variation_node );
3845  
3846                  // Update text indent selector for paragraph blocks based on the textIndent setting.
3847                  $variation_declarations = static::update_paragraph_text_indent_selector( $variation_declarations, $settings, $block_name );
3848  
3849                  // Update button width declarations for percentage values to use calc() with block gap.
3850                  $variation_declarations = static::update_button_width_declarations( $variation_declarations, $settings );
3851  
3852                  // Combine selectors with style variation's selector and add to overall style variation declarations.
3853                  foreach ( $variation_declarations as $current_selector => $new_declarations ) {
3854                      $combined_selectors = static::get_block_style_variation_feature_selector( $style_variation, $current_selector );
3855  
3856                      // Add the new declarations to the overall results under the modified selector.
3857                      $style_variation_declarations[ $combined_selectors ] = $new_declarations;
3858                  }
3859  
3860                  // Compute declarations for remaining styles not covered by feature level selectors.
3861                  $style_variation_declarations[ $style_variation['selector'] ] = static::compute_style_properties( $style_variation_node, $settings, null, $this->theme_json );
3862  
3863                  // Process pseudo-selectors for this variation (e.g., :hover, :focus)
3864                  if ( isset( $block_metadata['name'] ) ) {
3865                      $block_name = $block_metadata['name'];
3866                  } elseif ( in_array( 'blocks', $block_metadata['path'], true ) && count( $block_metadata['path'] ) >= 3 ) {
3867                      $block_name = static::get_block_name_from_metadata_path( $block_metadata );
3868                  } else {
3869                      $block_name = null;
3870                  }
3871                  $variation_pseudo_declarations = $this->process_pseudo_selectors( $style_variation_node, $style_variation['selector'], $settings, $block_name, $block_metadata, $style_variation );
3872                  $style_variation_declarations  = array_merge( $style_variation_declarations, $variation_pseudo_declarations );
3873  
3874                  // Store custom CSS for the style variation.
3875                  if ( isset( $style_variation_node['css'] ) ) {
3876                      $style_variation_custom_css[ $style_variation['selector'] ] = $this->process_blocks_custom_css( $style_variation_node['css'], $style_variation['selector'] );
3877                  }
3878  
3879                  // Store variation metadata and node for layout styles generation.
3880                  // Only store if the variation has blockGap defined.
3881                  if ( isset( $style_variation_node['spacing']['blockGap'] ) ) {
3882                      // Append block selector to the variation selector for proper targeting.
3883                      $variation_metadata_with_selector                                = $style_variation;
3884                      $variation_metadata_with_selector['selector']                    = $style_variation['selector'] . $block_metadata['css'];
3885                      $style_variation_layout_metadata[ $style_variation['selector'] ] = array(
3886                          'metadata' => $variation_metadata_with_selector,
3887                          'node'     => $style_variation_node,
3888                      );
3889                  }
3890  
3891                  // Store responsive breakpoint CSS for the style variation.
3892                  // This includes both base properties and feature-level selectors.
3893                  $variation_responsive_css        = '';
3894                  $variation_responsive_pseudo_css = '';
3895  
3896                  foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3897                      if ( ! isset( $style_variation_node[ $breakpoint ] ) ) {
3898                          continue;
3899                      }
3900  
3901                      $breakpoint_node  = $style_variation_node[ $breakpoint ];
3902                      $breakpoint_media = $responsive_media_queries[ $breakpoint ];
3903                      // Process feature-level declarations for this breakpoint.
3904                      $breakpoint_feature_declarations = static::get_feature_declarations_for_node( $block_metadata, $breakpoint_node );
3905                      $breakpoint_feature_declarations = static::update_paragraph_text_indent_selector( $breakpoint_feature_declarations, $settings, $block_name );
3906                      $breakpoint_feature_declarations = static::update_button_width_declarations( $breakpoint_feature_declarations, $settings );
3907                      foreach ( $breakpoint_feature_declarations as $feature_selector => $feature_decl ) {
3908                          $combined_selectors = static::get_block_style_variation_feature_selector( $style_variation, $feature_selector );
3909  
3910                          $feature_ruleset           = static::to_ruleset( ':root :where(' . $combined_selectors . ')', $feature_decl );
3911                          $variation_responsive_css .= $breakpoint_media . '{' . $feature_ruleset . '}';
3912                      }
3913  
3914                      // Process base properties for this breakpoint.
3915                      $breakpoint_declarations = static::compute_style_properties( $breakpoint_node, $settings, null, $this->theme_json );
3916                      if ( ! empty( $breakpoint_declarations ) ) {
3917                          $base_ruleset              = static::to_ruleset( ':root :where(' . $style_variation['selector'] . ')', $breakpoint_declarations );
3918                          $variation_responsive_css .= $breakpoint_media . '{' . $base_ruleset . '}';
3919                      }
3920  
3921                      $breakpoint_pseudo_declarations = $this->process_pseudo_selectors( $breakpoint_node, $style_variation['selector'], $settings, $block_name, $block_metadata, $style_variation );
3922                      foreach ( $breakpoint_pseudo_declarations as $pseudo_selector => $pseudo_declarations ) {
3923                          if ( empty( $pseudo_declarations ) ) {
3924                              continue;
3925                          }
3926                          $pseudo_ruleset                   = static::to_ruleset( ':root :where(' . $pseudo_selector . ')', $pseudo_declarations );
3927                          $variation_responsive_pseudo_css .= $breakpoint_media . '{' . $pseudo_ruleset . '}';
3928                      }
3929  
3930                      // Process custom CSS for this breakpoint.
3931                      if ( isset( $breakpoint_node['css'] ) ) {
3932                          $breakpoint_custom_css     = static::process_blocks_custom_css( $breakpoint_node['css'], $style_variation['selector'] );
3933                          $variation_responsive_css .= $breakpoint_media . '{' . $breakpoint_custom_css . '}';
3934                      }
3935  
3936                      // Process blockGap responsive layout styles for this variation.
3937                      if ( isset( $breakpoint_node['spacing']['blockGap'] ) ) {
3938                          $variation_layout_metadata             = $style_variation;
3939                          $variation_layout_metadata['selector'] = $style_variation['selector'] . $block_metadata['css'];
3940                          $variation_responsive_css             .= $this->get_layout_styles(
3941                              $variation_layout_metadata,
3942                              array(
3943                                  'node'        => $breakpoint_node,
3944                                  'media_query' => $breakpoint_media,
3945                              )
3946                          );
3947                      }
3948  
3949                      // Process nested element styles for this breakpoint state.
3950                      if ( isset( $breakpoint_node['elements'] ) && ! empty( $block_elements ) ) {
3951                          foreach ( $breakpoint_node['elements'] as $element_name => $element_node ) {
3952                              if ( ! isset( $block_elements[ $element_name ] ) ) {
3953                                  continue;
3954                              }
3955  
3956                              $variation_element_selector = static::get_block_style_variation_feature_selector( $style_variation, $block_elements[ $element_name ] );
3957  
3958                              $element_declarations = static::compute_style_properties( $element_node, $settings, null, $this->theme_json );
3959                              if ( ! empty( $element_declarations ) ) {
3960                                  $element_ruleset           = static::to_ruleset( ':root :where(' . $variation_element_selector . ')', $element_declarations );
3961                                  $variation_responsive_css .= $breakpoint_media . '{' . $element_ruleset . '}';
3962                              }
3963  
3964                              if ( isset( $element_node['css'] ) ) {
3965                                  $element_custom_css        = static::process_blocks_custom_css( $element_node['css'], $variation_element_selector );
3966                                  $variation_responsive_css .= $breakpoint_media . '{' . $element_custom_css . '}';
3967                              }
3968  
3969                              if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] ) ) {
3970                                  foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] as $pseudo_selector ) {
3971                                      if ( ! isset( $element_node[ $pseudo_selector ] ) ) {
3972                                          continue;
3973                                      }
3974  
3975                                      $pseudo_declarations = static::compute_style_properties( $element_node[ $pseudo_selector ], $settings, null, $this->theme_json );
3976                                      if ( empty( $pseudo_declarations ) ) {
3977                                          continue;
3978                                      }
3979  
3980                                      $pseudo_selector_ruleset          = static::to_ruleset( ':root :where(' . static::append_to_selector( $variation_element_selector, $pseudo_selector ) . ')', $pseudo_declarations );
3981                                      $variation_responsive_pseudo_css .= $breakpoint_media . '{' . $pseudo_selector_ruleset . '}';
3982                                  }
3983                              }
3984                          }
3985                      }
3986                  }
3987  
3988                  if ( ! empty( $variation_responsive_css ) ) {
3989                      $style_variation_responsive_css[ $style_variation['selector'] ] = $variation_responsive_css;
3990                  }
3991                  if ( ! empty( $variation_responsive_pseudo_css ) ) {
3992                      $style_variation_responsive_pseudo_css[ $style_variation['selector'] ] = $variation_responsive_pseudo_css;
3993                  }
3994              }
3995          }
3996          /*
3997           * Get a reference to element name from path.
3998           * $block_metadata['path'] = array( 'styles','elements','link' );
3999           * Make sure that $block_metadata['path'] describes an element node, like [ 'styles', 'element', 'link' ].
4000           * Skip non-element paths like just ['styles'].
4001           */
4002          $is_processing_element = in_array( 'elements', $block_metadata['path'], true );
4003  
4004          $current_element = $is_processing_element ? array_last( $block_metadata['path'] ) : null;
4005  
4006          $element_pseudo_allowed = array();
4007  
4008          if ( isset( $current_element, static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) ) {
4009              $element_pseudo_allowed = static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ];
4010          }
4011  
4012          /*
4013           * Check for allowed pseudo classes (e.g. ":hover") from the $selector ("a:hover").
4014           * This also resets the array keys.
4015           */
4016          $pseudo_matches = array_values(
4017              array_filter(
4018                  $element_pseudo_allowed,
4019                  static function ( $pseudo_selector ) use ( $selector ) {
4020                      /*
4021                       * Check if the pseudo selector is in the current selector,
4022                       * ensuring it is not followed by a dash (e.g., :focus should not match :focus-visible).
4023                       */
4024                      return preg_match( '/' . preg_quote( $pseudo_selector, '/' ) . '(?!-)/', $selector ) === 1;
4025                  }
4026              )
4027          );
4028  
4029          $pseudo_selector = $pseudo_matches[0] ?? null;
4030  
4031          /*
4032           * If the current selector is a pseudo selector that's defined in the allow list for the current
4033           * element then compute the style properties for it.
4034           * Otherwise just compute the styles for the default selector as normal.
4035           */
4036          if ( $pseudo_selector && isset( $node[ $pseudo_selector ] ) &&
4037              isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] )
4038              && in_array( $pseudo_selector, static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ], true )
4039          ) {
4040              $declarations = static::compute_style_properties( $node[ $pseudo_selector ], $settings, null, $this->theme_json, $selector, $use_root_padding );
4041          } else {
4042              /*
4043               * For block pseudo-selector nodes (e.g. ':hover'), $node has already had any
4044               * feature-selector properties (e.g. writingMode) removed by get_feature_declarations_for_node,
4045               * so those properties are not output twice.
4046               */
4047              $declarations = static::compute_style_properties( $node, $settings, null, $this->theme_json, $selector, $use_root_padding );
4048          }
4049  
4050          $block_rules = '';
4051  
4052          /*
4053           * 1. Bespoke declaration modifiers:
4054           * - 'filter': Separate the declarations that use the general selector
4055           * from the ones using the duotone selector.
4056           * - 'background|background-image': set the html min-height to 100%
4057           * to ensure the background covers the entire viewport.
4058           */
4059          $declarations_duotone       = array();
4060          $should_set_root_min_height = false;
4061  
4062          foreach ( $declarations as $index => $declaration ) {
4063              if ( 'filter' === $declaration['name'] ) {
4064                  /*
4065                   * 'unset' filters happen when a filter is unset
4066                   * in the site-editor UI. Because the 'unset' value
4067                   * in the user origin overrides the value in the
4068                   * theme origin, we can skip rendering anything
4069                   * here as no filter needs to be applied anymore.
4070                   * So only add declarations to with values other
4071                   * than 'unset'.
4072                   */
4073                  if ( 'unset' !== $declaration['value'] ) {
4074                      $declarations_duotone[] = $declaration;
4075                  }
4076                  unset( $declarations[ $index ] );
4077              }
4078  
4079              if ( $is_root_selector && ( 'background-image' === $declaration['name'] || 'background' === $declaration['name'] ) ) {
4080                  $should_set_root_min_height = true;
4081              }
4082          }
4083  
4084          /*
4085           * If root styles has a background-image or a background (gradient) set,
4086           * set the min-height to '100%'. Minus `--wp-admin--admin-bar--height` for logged-in view.
4087           * Setting the CSS rule on the HTML tag ensures background gradients and images behave similarly,
4088           * and matches the behavior of the site editor.
4089           */
4090          if ( $should_set_root_min_height ) {
4091              $block_rules .= static::to_ruleset(
4092                  'html',
4093                  array(
4094                      array(
4095                          'name'  => 'min-height',
4096                          'value' => 'calc(100% - var(--wp-admin--admin-bar--height, 0px))',
4097                      ),
4098                  )
4099              );
4100          }
4101  
4102          // Update declarations if there are separators with only background color defined.
4103          if ( '.wp-block-separator' === $selector ) {
4104              $declarations = static::update_separator_declarations( $declarations );
4105          }
4106  
4107          /*
4108           * Root selector (body) styles should not be wrapped in `:root where()` to keep
4109           * specificity at (0,0,1) and maintain backwards compatibility.
4110           *
4111           * Top-level element styles using element-only specificity selectors should
4112           * not get wrapped in `:root :where()` to maintain backwards compatibility.
4113           *
4114           * Pseudo classes, e.g. :hover, :focus etc., are a class-level selector so
4115           * still need to be wrapped in `:root :where` to cap specificity for nested
4116           * variations etc. Pseudo selectors won't match the ELEMENTS selector exactly.
4117           */
4118          $element_only_selector = $is_root_selector || (
4119              $current_element &&
4120              isset( static::ELEMENTS[ $current_element ] ) &&
4121              // buttons, captions etc. still need `:root :where()` as they are class based selectors.
4122              ! isset( static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $current_element ] ) &&
4123              static::ELEMENTS[ $current_element ] === $selector
4124          );
4125  
4126          // 2. Generate and append the rules that use the general selector.
4127          $general_selector = $element_only_selector ? $selector : ":root :where($selector)";
4128          $block_rules     .= static::to_ruleset( $general_selector, $declarations );
4129  
4130          // 3. Generate and append the rules that use the duotone selector.
4131          if ( isset( $block_metadata['duotone'] ) && ! empty( $declarations_duotone ) ) {
4132              $block_rules .= static::to_ruleset( $block_metadata['duotone'], $declarations_duotone );
4133          }
4134  
4135          // 4. Generate Layout block gap styles.
4136          if (
4137              ! $is_root_selector &&
4138              ! empty( $block_metadata['name'] )
4139          ) {
4140              $block_rules .= $this->get_layout_styles( $block_metadata );
4141          }
4142  
4143          // 5. Generate and append the feature level rulesets.
4144          foreach ( $feature_declarations as $feature_selector => $individual_feature_declarations ) {
4145              $block_rules .= static::to_ruleset( ":root :where($feature_selector)", $individual_feature_declarations );
4146          }
4147  
4148          // 6. Generate and append the style variation rulesets.
4149          foreach ( $style_variation_declarations as $style_variation_selector => $individual_style_variation_declarations ) {
4150              $block_rules .= static::to_ruleset( ":root :where($style_variation_selector)", $individual_style_variation_declarations );
4151              if ( isset( $style_variation_layout_metadata[ $style_variation_selector ] ) ) {
4152                  $variation_data = $style_variation_layout_metadata[ $style_variation_selector ];
4153                  $block_rules   .= $this->get_layout_styles( $variation_data['metadata'], array( 'node' => $variation_data['node'] ) );
4154              }
4155              if ( isset( $style_variation_custom_css[ $style_variation_selector ] ) ) {
4156                  $block_rules .= $style_variation_custom_css[ $style_variation_selector ];
4157              }
4158              if ( isset( $style_variation_responsive_css[ $style_variation_selector ] ) ) {
4159                  $block_rules .= $style_variation_responsive_css[ $style_variation_selector ];
4160              }
4161          }
4162          /*
4163           * Responsive pseudo styles must be output after default pseudo styles
4164           * so viewport state styles win in the cascade.
4165           */
4166          foreach ( $style_variation_responsive_pseudo_css as $responsive_pseudo_css ) {
4167              $block_rules .= $responsive_pseudo_css;
4168          }
4169  
4170          // 7. Generate and append any custom CSS rules.
4171          if ( isset( $node['css'] ) && ! $is_root_selector ) {
4172              $css_feature_selector = $block_metadata['selectors']['css'] ?? null;
4173              if ( is_array( $css_feature_selector ) ) {
4174                  $css_feature_selector = $css_feature_selector['root'] ?? null;
4175              }
4176              $css_selector = is_string( $css_feature_selector ) ? $css_feature_selector : $selector;
4177              $block_rules .= $this->process_blocks_custom_css( $node['css'], $css_selector );
4178          }
4179  
4180          // 8. Wrap the entire block output in a media query if this is a responsive node.
4181          // Responsive nodes are created by get_block_nodes() for each breakpoint and carry
4182          // a 'media_query' key.
4183          if ( $media_query && ! empty( $block_rules ) ) {
4184              $block_rules = $media_query . '{' . $block_rules . '}';
4185          }
4186  
4187          return $block_rules;
4188      }
4189  
4190      /**
4191       * Outputs the CSS for layout rules on the root.
4192       *
4193       * @since 6.1.0
4194       * @since 6.6.0 Use `ROOT_CSS_PROPERTIES_SELECTOR` for CSS custom properties and improved consistency of root padding rules.
4195       *              Updated specificity of body margin reset and first/last child selectors.
4196       * @since 7.0.0 Added `$options` parameter to control alignment styles output for classic themes.
4197       *
4198       * @param string $selector The root node selector.
4199       * @param array  $block_metadata The metadata for the root block.
4200       * @param array  $options        Optional. An array of options for now used for internal purposes only.
4201       * @return string The additional root rules CSS.
4202       */
4203  	public function get_root_layout_rules( $selector, $block_metadata, $options = array() ) {
4204          $css              = '';
4205          $settings         = $this->theme_json['settings'] ?? array();
4206          $use_root_padding = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments'];
4207  
4208          /*
4209           * If there are content and wide widths in theme.json, output them
4210           * as custom properties on the body element so all blocks can use them.
4211           */
4212          if ( isset( $settings['layout']['contentSize'] ) || isset( $settings['layout']['wideSize'] ) ) {
4213              $content_size = $settings['layout']['contentSize'] ?? $settings['layout']['wideSize'];
4214              $content_size = static::is_safe_css_declaration( 'max-width', $content_size ) ? $content_size : 'initial';
4215              $wide_size    = $settings['layout']['wideSize'] ?? $settings['layout']['contentSize'];
4216              $wide_size    = static::is_safe_css_declaration( 'max-width', $wide_size ) ? $wide_size : 'initial';
4217              $css         .= static::ROOT_CSS_PROPERTIES_SELECTOR . ' { --wp--style--global--content-size: ' . $content_size . ';';
4218              $css         .= '--wp--style--global--wide-size: ' . $wide_size . '; }';
4219          }
4220  
4221          /*
4222           * Reset default browser margin on the body element.
4223           * This is set on the body selector **before** generating the ruleset
4224           * from the `theme.json`. This is to ensure that if the `theme.json` declares
4225           * `margin` in its `spacing` declaration for the `body` element then these
4226           * user-generated values take precedence in the CSS cascade.
4227           * @link https://github.com/WordPress/gutenberg/issues/36147.
4228           */
4229          $css .= ':where(body) { margin: 0; }';
4230  
4231          if ( $use_root_padding ) {
4232              // Top and bottom padding are applied to the outer block container.
4233              $css .= '.wp-site-blocks { padding-top: var(--wp--style--root--padding-top); padding-bottom: var(--wp--style--root--padding-bottom); }';
4234              // Right and left padding are applied to the first container with `.has-global-padding` class.
4235              $css .= '.has-global-padding { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }';
4236              // Alignfull children of the container with left and right padding have negative margins so they can still be full width.
4237              $css .= '.has-global-padding > .alignfull { margin-right: calc(var(--wp--style--root--padding-right) * -1); margin-left: calc(var(--wp--style--root--padding-left) * -1); }';
4238              // Nested children of the container with left and right padding that are not full aligned do not get padding, unless they are direct children of an alignfull flow container.
4239              $css .= '.has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull)) { padding-right: 0; padding-left: 0; }';
4240              // Alignfull direct children of the containers that are targeted by the rule above do not need negative margins.
4241              $css .= '.has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull)) > .alignfull { margin-left: 0; margin-right: 0; }';
4242          }
4243  
4244          // Skip outputting alignment styles when base_layout_styles is enabled.
4245          // These styles target .wp-site-blocks which is only used by block themes.
4246          if ( empty( $options['base_layout_styles'] ) ) {
4247              $css .= '.wp-site-blocks > .alignleft { float: left; margin-right: 2em; }';
4248              $css .= '.wp-site-blocks > .alignright { float: right; margin-left: 2em; }';
4249              $css .= '.wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }';
4250          }
4251  
4252          // Block gap styles will be output unless explicitly set to `null`.
4253          if ( isset( $this->theme_json['settings']['spacing']['blockGap'] ) ) {
4254              $block_gap_value = static::get_property_value( $this->theme_json, array( 'styles', 'spacing', 'blockGap' ) );
4255              $css            .= ":where(.wp-site-blocks) > * { margin-block-start: $block_gap_value; margin-block-end: 0; }";
4256              $css            .= ':where(.wp-site-blocks) > :first-child { margin-block-start: 0; }';
4257              $css            .= ':where(.wp-site-blocks) > :last-child { margin-block-end: 0; }';
4258  
4259              // For backwards compatibility, ensure the legacy block gap CSS variable is still available.
4260              $css .= static::ROOT_CSS_PROPERTIES_SELECTOR . " { --wp--style--block-gap: $block_gap_value; }";
4261          }
4262          $css .= $this->get_layout_styles( $block_metadata, $options );
4263  
4264          return $css;
4265      }
4266  
4267      /**
4268       * For metadata values that can either be booleans or paths to booleans, gets the value.
4269       *
4270       *     $data = array(
4271       *       'color' => array(
4272       *         'defaultPalette' => true
4273       *       )
4274       *     );
4275       *
4276       *     static::get_metadata_boolean( $data, false );
4277       *     // => false
4278       *
4279       *     static::get_metadata_boolean( $data, array( 'color', 'defaultPalette' ) );
4280       *     // => true
4281       *
4282       * @since 6.0.0
4283       *
4284       * @param array      $data          The data to inspect.
4285       * @param bool|array $path          Boolean or path to a boolean.
4286       * @param bool       $default_value Default value if the referenced path is missing.
4287       *                                  Default false.
4288       * @return bool Value of boolean metadata.
4289       */
4290  	protected static function get_metadata_boolean( $data, $path, $default_value = false ) {
4291          if ( is_bool( $path ) ) {
4292              return $path;
4293          }
4294  
4295          if ( is_array( $path ) ) {
4296              $value = _wp_array_get( $data, $path );
4297              if ( null !== $value ) {
4298                  return $value;
4299              }
4300          }
4301  
4302          return $default_value;
4303      }
4304  
4305      /**
4306       * Merges new incoming data.
4307       *
4308       * @since 5.8.0
4309       * @since 5.9.0 Duotone preset also has origins.
4310       * @since 6.7.0 Replace background image objects during merge.
4311       *
4312       * @param WP_Theme_JSON $incoming Data to merge.
4313       */
4314  	public function merge( $incoming ) {
4315          $incoming_data    = $incoming->get_raw_data();
4316          $this->theme_json = array_replace_recursive( $this->theme_json, $incoming_data );
4317  
4318          /*
4319           * Recompute all the spacing sizes based on the new hierarchy of data. In the constructor
4320           * spacingScale and spacingSizes are both keyed by origin and VALID_ORIGINS is ordered, so
4321           * we can allow partial spacingScale data to inherit missing data from earlier layers when
4322           * computing the spacing sizes.
4323           *
4324           * This happens before the presets are merged to ensure that default spacing sizes can be
4325           * removed from the theme origin if $prevent_override is true.
4326           */
4327          $flattened_spacing_scale = array();
4328          foreach ( static::VALID_ORIGINS as $origin ) {
4329              $scale_path = array( 'settings', 'spacing', 'spacingScale', $origin );
4330  
4331              // Apply the base spacing scale to the current layer.
4332              $base_spacing_scale      = _wp_array_get( $this->theme_json, $scale_path, array() );
4333              $flattened_spacing_scale = array_replace( $flattened_spacing_scale, $base_spacing_scale );
4334  
4335              $spacing_scale = _wp_array_get( $incoming_data, $scale_path, null );
4336              if ( ! isset( $spacing_scale ) ) {
4337                  continue;
4338              }
4339  
4340              // Allow partial scale settings by merging with lower layers.
4341              $flattened_spacing_scale = array_replace( $flattened_spacing_scale, $spacing_scale );
4342  
4343              // Generate and merge the scales for this layer.
4344              $sizes_path           = array( 'settings', 'spacing', 'spacingSizes', $origin );
4345              $spacing_sizes        = _wp_array_get( $incoming_data, $sizes_path, array() );
4346              $spacing_scale_sizes  = static::compute_spacing_sizes( $flattened_spacing_scale );
4347              $merged_spacing_sizes = static::merge_spacing_sizes( $spacing_scale_sizes, $spacing_sizes );
4348  
4349              _wp_array_set( $incoming_data, $sizes_path, $merged_spacing_sizes );
4350          }
4351  
4352          /*
4353           * The array_replace_recursive algorithm merges at the leaf level,
4354           * but we don't want leaf arrays to be merged, so we overwrite it.
4355           *
4356           * For leaf values that are sequential arrays it will use the numeric indexes for replacement.
4357           * We rather replace the existing with the incoming value, if it exists.
4358           * This is the case of spacing.units.
4359           *
4360           * For leaf values that are associative arrays it will merge them as expected.
4361           * This is also not the behavior we want for the current associative arrays (presets).
4362           * We rather replace the existing with the incoming value, if it exists.
4363           * This happens, for example, when we merge data from theme.json upon existing
4364           * theme supports or when we merge anything coming from the same source twice.
4365           * This is the case of color.palette, color.gradients, color.duotone,
4366           * typography.fontSizes, or typography.fontFamilies.
4367           *
4368           * Additionally, for some preset types, we also want to make sure the
4369           * values they introduce don't conflict with default values. We do so
4370           * by checking the incoming slugs for theme presets and compare them
4371           * with the equivalent default presets: if a slug is present as a default
4372           * we remove it from the theme presets.
4373           */
4374          $nodes        = static::get_setting_nodes( $incoming_data );
4375          $slugs_global = static::get_default_slugs( $this->theme_json, array( 'settings' ) );
4376          foreach ( $nodes as $node ) {
4377              // Replace the spacing.units.
4378              $path   = $node['path'];
4379              $path[] = 'spacing';
4380              $path[] = 'units';
4381  
4382              $content = _wp_array_get( $incoming_data, $path, null );
4383              if ( isset( $content ) ) {
4384                  _wp_array_set( $this->theme_json, $path, $content );
4385              }
4386  
4387              // Replace the presets.
4388              foreach ( static::PRESETS_METADATA as $preset_metadata ) {
4389                  $prevent_override = $preset_metadata['prevent_override'];
4390                  if ( is_array( $prevent_override ) ) {
4391                      $global_path  = array_merge( array( 'settings' ), $prevent_override );
4392                      $global_value = _wp_array_get( $this->theme_json, $global_path, null );
4393  
4394                      $node_level_path  = array_merge( $node['path'], $prevent_override );
4395                      $prevent_override = _wp_array_get( $this->theme_json, $node_level_path, $global_value );
4396                  }
4397  
4398                  foreach ( static::VALID_ORIGINS as $origin ) {
4399                      $base_path = $node['path'];
4400                      foreach ( $preset_metadata['path'] as $leaf ) {
4401                          $base_path[] = $leaf;
4402                      }
4403  
4404                      $path   = $base_path;
4405                      $path[] = $origin;
4406  
4407                      $content = _wp_array_get( $incoming_data, $path, null );
4408                      if ( ! isset( $content ) ) {
4409                          continue;
4410                      }
4411  
4412                      // Set names for theme presets based on the slug if they are not set and can use default names.
4413                      if ( 'theme' === $origin && $preset_metadata['use_default_names'] ) {
4414                          foreach ( $content as $key => $item ) {
4415                              if ( ! isset( $item['name'] ) ) {
4416                                  $name = static::get_name_from_defaults( $item['slug'], $base_path );
4417                                  if ( null !== $name ) {
4418                                      $content[ $key ]['name'] = $name;
4419                                  }
4420                              }
4421                          }
4422                      }
4423  
4424                      // Filter out default slugs from theme presets when defaults should not be overridden.
4425                      if ( 'theme' === $origin && $prevent_override ) {
4426                          $slugs_node    = static::get_default_slugs( $this->theme_json, $node['path'] );
4427                          $preset_global = _wp_array_get( $slugs_global, $preset_metadata['path'], array() );
4428                          $preset_node   = _wp_array_get( $slugs_node, $preset_metadata['path'], array() );
4429                          $preset_slugs  = array_merge_recursive( $preset_global, $preset_node );
4430  
4431                          $content = static::filter_slugs( $content, $preset_slugs );
4432                      }
4433  
4434                      _wp_array_set( $this->theme_json, $path, $content );
4435                  }
4436              }
4437          }
4438  
4439          /*
4440           * Style values are merged at the leaf level, however
4441           * some values provide exceptions, namely style values that are
4442           * objects and represent unique definitions for the style.
4443           */
4444          $style_nodes = static::get_block_nodes(
4445              $this->theme_json,
4446              array(),
4447              array( 'include_node_paths_only' => true )
4448          );
4449  
4450          // Add top-level styles.
4451          $style_nodes[] = array( 'path' => array( 'styles' ) );
4452  
4453          foreach ( $style_nodes as $style_node ) {
4454              $path = $style_node['path'];
4455              /*
4456               * Background image styles should be replaced, not merged,
4457               * as they themselves are specific object definitions for the style.
4458               */
4459              $background_image_path = array_merge( $path, static::PROPERTIES_METADATA['background-image'] );
4460              $content               = _wp_array_get( $incoming_data, $background_image_path, null );
4461              if ( isset( $content ) ) {
4462                  _wp_array_set( $this->theme_json, $background_image_path, $content );
4463              }
4464          }
4465      }
4466  
4467      /**
4468       * Converts all filter (duotone) presets into SVGs.
4469       *
4470       * @since 5.9.1
4471       *
4472       * @param array $origins List of origins to process.
4473       * @return string SVG filters.
4474       */
4475  	public function get_svg_filters( $origins ) {
4476          $blocks_metadata = static::get_blocks_metadata();
4477          $setting_nodes   = static::get_setting_nodes( $this->theme_json, $blocks_metadata );
4478  
4479          $filters = '';
4480          foreach ( $setting_nodes as $metadata ) {
4481              $node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
4482              if ( empty( $node['color']['duotone'] ) ) {
4483                  continue;
4484              }
4485  
4486              $duotone_presets = $node['color']['duotone'];
4487  
4488              foreach ( $origins as $origin ) {
4489                  if ( ! isset( $duotone_presets[ $origin ] ) ) {
4490                      continue;
4491                  }
4492                  foreach ( $duotone_presets[ $origin ] as $duotone_preset ) {
4493                      $filters .= WP_Duotone::get_filter_svg_from_preset( $duotone_preset );
4494                  }
4495              }
4496          }
4497  
4498          return $filters;
4499      }
4500  
4501      /**
4502       * Determines whether a presets should be overridden or not.
4503       *
4504       * @since 5.9.0
4505       * @deprecated 6.0.0 Use {@see 'get_metadata_boolean'} instead.
4506       *
4507       * @param array      $theme_json The theme.json like structure to inspect.
4508       * @param array      $path       Path to inspect.
4509       * @param bool|array $override   Data to compute whether to override the preset.
4510       * @return bool|null True if the preset should override the defaults, false if not. Null if the override parameter is invalid.
4511       */
4512  	protected static function should_override_preset( $theme_json, $path, $override ) {
4513          _deprecated_function( __METHOD__, '6.0.0', 'get_metadata_boolean' );
4514  
4515          if ( is_bool( $override ) ) {
4516              return $override;
4517          }
4518  
4519          /*
4520           * The relationship between whether to override the defaults
4521           * and whether the defaults are enabled is inverse:
4522           *
4523           * - If defaults are enabled  => theme presets should not be overridden
4524           * - If defaults are disabled => theme presets should be overridden
4525           *
4526           * For example, a theme sets defaultPalette to false,
4527           * making the default palette hidden from the user.
4528           * In that case, we want all the theme presets to be present,
4529           * so they should override the defaults.
4530           */
4531          if ( is_array( $override ) ) {
4532              $value = _wp_array_get( $theme_json, array_merge( $path, $override ) );
4533              if ( isset( $value ) ) {
4534                  return ! $value;
4535              }
4536  
4537              // Search the top-level key if none was found for this node.
4538              $value = _wp_array_get( $theme_json, array_merge( array( 'settings' ), $override ) );
4539              if ( isset( $value ) ) {
4540                  return ! $value;
4541              }
4542  
4543              return true;
4544          }
4545  
4546          return null;
4547      }
4548  
4549      /**
4550       * Returns the default slugs for all the presets in an associative array
4551       * whose keys are the preset paths and the leaves is the list of slugs.
4552       *
4553       * For example:
4554       *
4555       *     array(
4556       *       'color' => array(
4557       *         'palette'   => array( 'slug-1', 'slug-2' ),
4558       *         'gradients' => array( 'slug-3', 'slug-4' ),
4559       *       ),
4560       *     )
4561       *
4562       * @since 5.9.0
4563       *
4564       * @param array $data      A theme.json like structure.
4565       * @param array $node_path The path to inspect. It's 'settings' by default.
4566       * @return array
4567       */
4568  	protected static function get_default_slugs( $data, $node_path ) {
4569          $slugs = array();
4570  
4571          foreach ( static::PRESETS_METADATA as $metadata ) {
4572              $path = $node_path;
4573              foreach ( $metadata['path'] as $leaf ) {
4574                  $path[] = $leaf;
4575              }
4576              $path[] = 'default';
4577  
4578              $preset = _wp_array_get( $data, $path, null );
4579              if ( ! isset( $preset ) ) {
4580                  continue;
4581              }
4582  
4583              $slugs_for_preset = array();
4584              foreach ( $preset as $item ) {
4585                  if ( isset( $item['slug'] ) ) {
4586                      $slugs_for_preset[] = $item['slug'];
4587                  }
4588              }
4589  
4590              _wp_array_set( $slugs, $metadata['path'], $slugs_for_preset );
4591          }
4592  
4593          return $slugs;
4594      }
4595  
4596      /**
4597       * Gets a `default`'s preset name by a provided slug.
4598       *
4599       * @since 5.9.0
4600       *
4601       * @param string $slug The slug we want to find a match from default presets.
4602       * @param array  $base_path The path to inspect. It's 'settings' by default.
4603       * @return string|null
4604       */
4605  	protected function get_name_from_defaults( $slug, $base_path ) {
4606          $path            = $base_path;
4607          $path[]          = 'default';
4608          $default_content = _wp_array_get( $this->theme_json, $path, null );
4609          if ( ! $default_content ) {
4610              return null;
4611          }
4612          foreach ( $default_content as $item ) {
4613              if ( $slug === $item['slug'] ) {
4614                  return $item['name'];
4615              }
4616          }
4617          return null;
4618      }
4619  
4620      /**
4621       * Removes the preset values whose slug is equal to any of given slugs.
4622       *
4623       * @since 5.9.0
4624       *
4625       * @param array $node  The node with the presets to validate.
4626       * @param array $slugs The slugs that should not be overridden.
4627       * @return array The new node.
4628       */
4629  	protected static function filter_slugs( $node, $slugs ) {
4630          if ( empty( $slugs ) ) {
4631              return $node;
4632          }
4633  
4634          $new_node = array();
4635          foreach ( $node as $value ) {
4636              if ( isset( $value['slug'] ) && ! in_array( $value['slug'], $slugs, true ) ) {
4637                  $new_node[] = $value;
4638              }
4639          }
4640  
4641          return $new_node;
4642      }
4643  
4644      /**
4645       * Removes insecure data from theme.json.
4646       *
4647       * @since 5.9.0
4648       * @since 6.3.2 Preserves global styles block variations when securing styles.
4649       * @since 6.6.0 Updated to allow variation element styles and $origin parameter.
4650       *
4651       * @param array  $theme_json Structure to sanitize.
4652       * @param string $origin     Optional. What source of data this object represents.
4653       *                           One of 'blocks', 'default', 'theme', or 'custom'. Default 'theme'.
4654       * @return array Sanitized structure.
4655       */
4656  	public static function remove_insecure_properties( $theme_json, $origin = 'theme' ) {
4657          if ( ! in_array( $origin, static::VALID_ORIGINS, true ) ) {
4658              $origin = 'theme';
4659          }
4660  
4661          $sanitized = array();
4662  
4663          $theme_json = WP_Theme_JSON_Schema::migrate( $theme_json, $origin );
4664  
4665          $blocks_metadata     = static::get_blocks_metadata();
4666          $valid_block_names   = array_keys( $blocks_metadata );
4667          $valid_element_names = array_keys( static::ELEMENTS );
4668          $valid_variations    = static::get_valid_block_style_variations( $blocks_metadata );
4669  
4670          $theme_json = static::sanitize( $theme_json, $valid_block_names, $valid_element_names, $valid_variations );
4671  
4672          $blocks_metadata          = static::get_blocks_metadata();
4673          $style_options            = array( 'include_block_style_variations' => true ); // Allow variations data.
4674          $style_nodes              = static::get_style_nodes( $theme_json, $blocks_metadata, $style_options );
4675          $responsive_media_queries = static::get_viewport_media_queries( $theme_json['settings']['viewport'] ?? null );
4676  
4677          foreach ( $style_nodes as $metadata ) {
4678              $input = _wp_array_get( $theme_json, $metadata['path'], array() );
4679              if ( empty( $input ) ) {
4680                  continue;
4681              }
4682  
4683              $block_name = in_array( 'blocks', $metadata['path'], true )
4684                  ? static::get_block_name_from_metadata_path( $metadata )
4685                  : null;
4686  
4687              // The global styles custom CSS is not sanitized, but can only be edited by users with 'edit_css' capability.
4688              if ( isset( $input['css'] ) && current_user_can( 'edit_css' ) ) {
4689                  $output = $input;
4690              } else {
4691                  $output = static::remove_insecure_styles( $input );
4692              }
4693  
4694              /*
4695               * Get a reference to element name from path.
4696               * $metadata['path'] = array( 'styles', 'elements', 'link' );
4697               */
4698              $current_element = array_last( $metadata['path'] );
4699  
4700              /*
4701               * $output is stripped of pseudo selectors. Re-add and process them
4702               * or insecure styles here.
4703               */
4704              if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) ) {
4705                  foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] as $pseudo_selector ) {
4706                      if ( isset( $input[ $pseudo_selector ] ) ) {
4707                          $output[ $pseudo_selector ] = static::remove_insecure_styles( $input[ $pseudo_selector ] );
4708                      }
4709                  }
4710              }
4711  
4712              // Re-add and process responsive breakpoint styles.
4713              foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
4714                  if ( isset( $input[ $breakpoint ] ) ) {
4715                      $output[ $breakpoint ] = static::remove_insecure_styles( $input[ $breakpoint ] );
4716  
4717                      if ( isset( $input[ $breakpoint ]['elements'] ) ) {
4718                          $output[ $breakpoint ]['elements'] = static::remove_insecure_element_styles( $input[ $breakpoint ]['elements'], $responsive_media_queries );
4719                      }
4720  
4721                      if ( isset( $input[ $breakpoint ]['blocks'] ) ) {
4722                          $output[ $breakpoint ]['blocks'] = static::remove_insecure_inner_block_styles( $input[ $breakpoint ]['blocks'], $responsive_media_queries );
4723                      }
4724  
4725                      if ( $block_name && isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_name ] ) ) {
4726                          foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_name ] as $pseudo_selector ) {
4727                              if ( isset( $input[ $breakpoint ][ $pseudo_selector ] ) ) {
4728                                  $output[ $breakpoint ][ $pseudo_selector ] = static::remove_insecure_styles( $input[ $breakpoint ][ $pseudo_selector ] );
4729                              }
4730                          }
4731                      }
4732  
4733                      // Responsive custom CSS is allowed for users with 'edit_css' capability.
4734                      if ( isset( $input[ $breakpoint ]['css'] ) && current_user_can( 'edit_css' ) ) {
4735                          $output[ $breakpoint ]['css'] = $input[ $breakpoint ]['css'];
4736                      }
4737                  }
4738              }
4739  
4740              if ( ! empty( $output ) ) {
4741                  _wp_array_set( $sanitized, $metadata['path'], $output );
4742              }
4743  
4744              if ( isset( $metadata['variations'] ) ) {
4745                  foreach ( $metadata['variations'] as $variation ) {
4746                      $variation_input = _wp_array_get( $theme_json, $variation['path'], array() );
4747                      if ( empty( $variation_input ) ) {
4748                          continue;
4749                      }
4750  
4751                      $variation_output = static::remove_insecure_styles( $variation_input );
4752  
4753                      if ( isset( $variation_input['blocks'] ) ) {
4754                          $variation_output['blocks'] = static::remove_insecure_inner_block_styles( $variation_input['blocks'], $responsive_media_queries );
4755                      }
4756  
4757                      if ( isset( $variation_input['elements'] ) ) {
4758                          $variation_output['elements'] = static::remove_insecure_element_styles( $variation_input['elements'], $responsive_media_queries );
4759                      }
4760  
4761                      // Re-add and process responsive breakpoint styles for variations.
4762                      foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
4763                          if ( isset( $variation_input[ $breakpoint ] ) ) {
4764                              $variation_output[ $breakpoint ] = static::remove_insecure_styles( $variation_input[ $breakpoint ] );
4765  
4766                              if ( isset( $variation_input[ $breakpoint ]['elements'] ) ) {
4767                                  $variation_output[ $breakpoint ]['elements'] = static::remove_insecure_element_styles( $variation_input[ $breakpoint ]['elements'], $responsive_media_queries );
4768                              }
4769  
4770                              if ( isset( $variation_input[ $breakpoint ]['blocks'] ) ) {
4771                                  $variation_output[ $breakpoint ]['blocks'] = static::remove_insecure_inner_block_styles( $variation_input[ $breakpoint ]['blocks'], $responsive_media_queries );
4772                              }
4773  
4774                              if ( $block_name && isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_name ] ) ) {
4775                                  foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_name ] as $pseudo_selector ) {
4776                                      if ( isset( $variation_input[ $breakpoint ][ $pseudo_selector ] ) ) {
4777                                          $variation_output[ $breakpoint ][ $pseudo_selector ] = static::remove_insecure_styles( $variation_input[ $breakpoint ][ $pseudo_selector ] );
4778                                      }
4779                                  }
4780                              }
4781  
4782                              // Responsive custom CSS is allowed for users with 'edit_css' capability.
4783                              if ( isset( $variation_input[ $breakpoint ]['css'] ) && current_user_can( 'edit_css' ) ) {
4784                                  $variation_output[ $breakpoint ]['css'] = $variation_input[ $breakpoint ]['css'];
4785                              }
4786                          }
4787                      }
4788  
4789                      if ( ! empty( $variation_output ) ) {
4790                          _wp_array_set( $sanitized, $variation['path'], $variation_output );
4791                      }
4792                  }
4793              }
4794          }
4795  
4796          $setting_nodes = static::get_setting_nodes( $theme_json );
4797          foreach ( $setting_nodes as $metadata ) {
4798              $input = _wp_array_get( $theme_json, $metadata['path'], array() );
4799              if ( empty( $input ) ) {
4800                  continue;
4801              }
4802  
4803              $output = static::remove_insecure_settings( $input, array( 'settings' ) === $metadata['path'] );
4804              if ( ! empty( $output ) ) {
4805                  _wp_array_set( $sanitized, $metadata['path'], $output );
4806              }
4807          }
4808  
4809          if ( empty( $sanitized['styles'] ) ) {
4810              unset( $theme_json['styles'] );
4811          } else {
4812              $theme_json['styles'] = $sanitized['styles'];
4813          }
4814  
4815          if ( empty( $sanitized['settings'] ) ) {
4816              unset( $theme_json['settings'] );
4817          } else {
4818              $theme_json['settings'] = $sanitized['settings'];
4819          }
4820  
4821          return $theme_json;
4822      }
4823  
4824      /**
4825       * Remove insecure element styles within a variation or block.
4826       *
4827       *  * When responsive media queries are provided, nested responsive state styles
4828       * matching those viewport state keys are re-added after the base sanitization pass.
4829       *
4830       * @since 6.8.0
4831       * @since 7.1.0 Added the `$responsive_media_queries` parameter.
4832       *
4833       * @param array      $elements                 The elements to process.
4834       * @param array|null $responsive_media_queries Optional. Media queries whose keys define allowed
4835       *                                             viewport states. Default null.
4836       * @return array The sanitized elements styles.
4837       */
4838  	protected static function remove_insecure_element_styles( $elements, $responsive_media_queries = null ) {
4839          $sanitized           = array();
4840          $valid_element_names = array_keys( static::ELEMENTS );
4841  
4842          foreach ( $valid_element_names as $element_name ) {
4843              $element_input = $elements[ $element_name ] ?? null;
4844              if ( $element_input ) {
4845                  $element_output = static::remove_insecure_styles( $element_input );
4846  
4847                  if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] ) ) {
4848                      foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] as $pseudo_selector ) {
4849                          if ( isset( $element_input[ $pseudo_selector ] ) ) {
4850                              $element_output[ $pseudo_selector ] = static::remove_insecure_styles( $element_input[ $pseudo_selector ] );
4851                          }
4852                      }
4853                  }
4854  
4855                  if ( null !== $responsive_media_queries ) {
4856                      // Re-add and process responsive breakpoint styles for elements.
4857                      foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
4858                          if ( isset( $element_input[ $breakpoint ] ) ) {
4859                              $element_output[ $breakpoint ] = static::remove_insecure_styles( $element_input[ $breakpoint ] );
4860  
4861                              if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] ) ) {
4862                                  foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] as $pseudo_selector ) {
4863                                      if ( isset( $element_input[ $breakpoint ][ $pseudo_selector ] ) ) {
4864                                          $element_output[ $breakpoint ][ $pseudo_selector ] = static::remove_insecure_styles( $element_input[ $breakpoint ][ $pseudo_selector ] );
4865                                      }
4866                                  }
4867                              }
4868                          }
4869                      }
4870                  }
4871  
4872                  $sanitized[ $element_name ] = $element_output;
4873              }
4874          }
4875          return $sanitized;
4876      }
4877  
4878      /**
4879       * Remove insecure styles from inner blocks and their elements.
4880       *
4881       * When responsive media queries are provided, nested responsive state styles
4882       * for those media-query keys are re-added after the base sanitization pass.
4883       *
4884       * @since 6.8.0
4885       * @since 7.1.0 Added the `$responsive_media_queries` parameter.
4886       *
4887       * @param array      $blocks                   The block styles to process.
4888       * @param array|null $responsive_media_queries Optional. Media queries whose keys define allowed
4889       *                                             viewport states. Default null.
4890       * @return array Sanitized block type styles.
4891       */
4892  	protected static function remove_insecure_inner_block_styles( $blocks, $responsive_media_queries = null ) {
4893          $sanitized = array();
4894          foreach ( $blocks as $block_type => $block_input ) {
4895              $block_output = static::remove_insecure_styles( $block_input );
4896  
4897              if ( isset( $block_input['elements'] ) ) {
4898                  $block_output['elements'] = static::remove_insecure_element_styles( $block_input['elements'], $responsive_media_queries );
4899              }
4900  
4901              if ( null !== $responsive_media_queries ) {
4902                  // Re-add and process responsive breakpoint styles for inner blocks.
4903                  foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
4904                      if ( isset( $block_input[ $breakpoint ] ) ) {
4905                          $block_output[ $breakpoint ] = static::remove_insecure_styles( $block_input[ $breakpoint ] );
4906  
4907                          if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_type ] ) ) {
4908                              foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_type ] as $pseudo_selector ) {
4909                                  if ( isset( $block_input[ $breakpoint ][ $pseudo_selector ] ) ) {
4910                                      $block_output[ $breakpoint ][ $pseudo_selector ] = static::remove_insecure_styles( $block_input[ $breakpoint ][ $pseudo_selector ] );
4911                                  }
4912                              }
4913                          }
4914                      }
4915                  }
4916              }
4917  
4918              $sanitized[ $block_type ] = $block_output;
4919          }
4920          return $sanitized;
4921      }
4922  
4923      /**
4924       * Preserves valid typed settings from input to output based on type markers in schema.
4925       *
4926       * Recursively iterates through the schema and validates/preserves settings
4927       * that have type markers (e.g., boolean) in VALID_SETTINGS.
4928       *
4929       * @since 7.0.0
4930       *
4931       * @param array             $input  Input settings to process.
4932       * @param array             $output Output settings array (passed by reference).
4933       * @param array             $schema Schema to validate against (typically VALID_SETTINGS).
4934       * @param array<string|int> $path   Current path in the schema (for recursive calls).
4935       */
4936  	private static function preserve_valid_typed_settings( $input, &$output, $schema, $path = array() ) {
4937          foreach ( $schema as $key => $schema_value ) {
4938              $current_path = array_merge( $path, array( $key ) );
4939  
4940              // Validate boolean type markers.
4941              if ( is_bool( $schema_value ) ) {
4942                  $value = _wp_array_get( $input, $current_path, null );
4943                  if ( is_bool( $value ) ) {
4944                      _wp_array_set( $output, $current_path, $value ); // Preserve boolean value.
4945                  }
4946              } elseif ( is_array( $schema_value ) ) {
4947                  self::preserve_valid_typed_settings( $input, $output, $schema_value, $current_path ); // Recurse into nested structure.
4948              }
4949          }
4950      }
4951  
4952      /**
4953       * Processes a setting node and returns the same node
4954       * without the insecure settings.
4955       *
4956       * @since 5.9.0
4957       * @since 7.1.0 Added the `$is_root` parameter.
4958       *
4959       * @param array $input   Node to process.
4960       * @param bool  $is_root Optional. Whether the node is the root settings node. Default false.
4961       * @return array
4962       */
4963  	protected static function remove_insecure_settings( $input, $is_root = false ) {
4964          $output = array();
4965          foreach ( static::PRESETS_METADATA as $preset_metadata ) {
4966              foreach ( static::VALID_ORIGINS as $origin ) {
4967                  $path_with_origin   = $preset_metadata['path'];
4968                  $path_with_origin[] = $origin;
4969                  $presets            = _wp_array_get( $input, $path_with_origin, null );
4970                  if ( null === $presets ) {
4971                      continue;
4972                  }
4973  
4974                  $escaped_preset = array();
4975                  foreach ( $presets as $preset ) {
4976                      if (
4977                          esc_attr( esc_html( $preset['name'] ) ) === $preset['name'] &&
4978                          sanitize_html_class( $preset['slug'] ) === $preset['slug']
4979                      ) {
4980                          $value = null;
4981                          if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) {
4982                              $value = $preset[ $preset_metadata['value_key'] ];
4983                          } elseif (
4984                              isset( $preset_metadata['value_func'] ) &&
4985                              is_callable( $preset_metadata['value_func'] )
4986                          ) {
4987                              $value = call_user_func( $preset_metadata['value_func'], $preset );
4988                          }
4989  
4990                          $preset_is_valid = true;
4991                          foreach ( $preset_metadata['properties'] as $property ) {
4992                              if ( ! static::is_safe_css_declaration( $property, $value ) ) {
4993                                  $preset_is_valid = false;
4994                                  break;
4995                              }
4996                          }
4997  
4998                          if ( $preset_is_valid ) {
4999                              $escaped_preset[] = $preset;
5000                          }
5001                      }
5002                  }
5003  
5004                  if ( ! empty( $escaped_preset ) ) {
5005                      _wp_array_set( $output, $path_with_origin, $escaped_preset );
5006                  }
5007              }
5008          }
5009  
5010          // Ensure indirect properties not included in any `PRESETS_METADATA` value are allowed.
5011          static::remove_indirect_properties( $input, $output );
5012  
5013          // Preserve all valid settings that have type markers in VALID_SETTINGS.
5014          self::preserve_valid_typed_settings( $input, $output, static::VALID_SETTINGS );
5015  
5016          if ( $is_root && array_key_exists( 'viewport', $input ) ) {
5017              $output['viewport'] = static::sanitize_viewport_settings( $input['viewport'] );
5018          }
5019  
5020          return $output;
5021      }
5022  
5023      /**
5024       * Processes a style node and returns the same node
5025       * without the insecure styles.
5026       *
5027       * @since 5.9.0
5028       *
5029       * @param array $input Node to process.
5030       * @return array
5031       */
5032  	protected static function remove_insecure_styles( $input ) {
5033          $output       = array();
5034          $declarations = static::compute_style_properties( $input );
5035  
5036          foreach ( $declarations as $declaration ) {
5037              if ( static::is_safe_css_declaration( $declaration['name'], $declaration['value'] ) ) {
5038                  $path = static::PROPERTIES_METADATA[ $declaration['name'] ];
5039  
5040                  /*
5041                   * Check the value isn't an array before adding so as to not
5042                   * double up shorthand and longhand styles.
5043                   */
5044                  $value = _wp_array_get( $input, $path, array() );
5045                  if ( ! is_array( $value ) ) {
5046                      _wp_array_set( $output, $path, $value );
5047                  }
5048              }
5049          }
5050  
5051          // Ensure indirect properties not handled by `compute_style_properties` are allowed.
5052          static::remove_indirect_properties( $input, $output );
5053  
5054          return $output;
5055      }
5056  
5057      /**
5058       * Checks that a declaration provided by the user is safe.
5059       *
5060       * @since 5.9.0
5061       *
5062       * @param string $property_name  Property name in a CSS declaration, i.e. the `color` in `color: red`.
5063       * @param string $property_value Value in a CSS declaration, i.e. the `red` in `color: red`.
5064       * @return bool
5065       */
5066  	protected static function is_safe_css_declaration( $property_name, $property_value ) {
5067          $style_to_validate = $property_name . ': ' . $property_value;
5068          $filtered          = esc_html( safecss_filter_attr( $style_to_validate ) );
5069          return ! empty( trim( $filtered ) );
5070      }
5071  
5072      /**
5073       * Removes indirect properties from the given input node and
5074       * sets in the given output node.
5075       *
5076       * @since 6.2.0
5077       *
5078       * @param array $input  Node to process.
5079       * @param array $output The processed node. Passed by reference.
5080       */
5081  	private static function remove_indirect_properties( $input, &$output ) {
5082          foreach ( static::INDIRECT_PROPERTIES_METADATA as $property => $paths ) {
5083              foreach ( $paths as $path ) {
5084                  $value = _wp_array_get( $input, $path );
5085                  if (
5086                      is_string( $value ) &&
5087                      static::is_safe_css_declaration( $property, $value )
5088                  ) {
5089                      _wp_array_set( $output, $path, $value );
5090                  }
5091              }
5092          }
5093      }
5094  
5095      /**
5096       * Returns the raw data.
5097       *
5098       * @since 5.8.0
5099       *
5100       * @return array Raw data.
5101       */
5102  	public function get_raw_data() {
5103          return $this->theme_json;
5104      }
5105  
5106      /**
5107       * Transforms the given editor settings according the
5108       * add_theme_support format to the theme.json format.
5109       *
5110       * @since 5.8.0
5111       *
5112       * @param array $settings Existing editor settings.
5113       * @return array Config that adheres to the theme.json schema.
5114       */
5115  	public static function get_from_editor_settings( $settings ) {
5116          $theme_settings = array(
5117              'version'  => static::LATEST_SCHEMA,
5118              'settings' => array(),
5119          );
5120  
5121          // Deprecated theme supports.
5122          if ( isset( $settings['disableCustomColors'] ) ) {
5123              $theme_settings['settings']['color']['custom'] = ! $settings['disableCustomColors'];
5124          }
5125  
5126          if ( isset( $settings['disableCustomGradients'] ) ) {
5127              $theme_settings['settings']['color']['customGradient'] = ! $settings['disableCustomGradients'];
5128          }
5129  
5130          if ( isset( $settings['disableCustomFontSizes'] ) ) {
5131              $theme_settings['settings']['typography']['customFontSize'] = ! $settings['disableCustomFontSizes'];
5132          }
5133  
5134          if ( isset( $settings['enableCustomLineHeight'] ) ) {
5135              $theme_settings['settings']['typography']['lineHeight'] = $settings['enableCustomLineHeight'];
5136          }
5137  
5138          if ( isset( $settings['enableCustomUnits'] ) ) {
5139              $theme_settings['settings']['spacing']['units'] = ( true === $settings['enableCustomUnits'] ) ?
5140                  array( 'px', 'em', 'rem', 'vh', 'vw', '%' ) :
5141                  $settings['enableCustomUnits'];
5142          }
5143  
5144          if ( isset( $settings['colors'] ) ) {
5145              $theme_settings['settings']['color']['palette'] = $settings['colors'];
5146          }
5147  
5148          if ( isset( $settings['gradients'] ) ) {
5149              $theme_settings['settings']['color']['gradients'] = $settings['gradients'];
5150          }
5151  
5152          if ( isset( $settings['fontSizes'] ) ) {
5153              $font_sizes = $settings['fontSizes'];
5154              // Back-compatibility for presets without units.
5155              foreach ( $font_sizes as $key => $font_size ) {
5156                  if ( is_numeric( $font_size['size'] ) ) {
5157                      $font_sizes[ $key ]['size'] = $font_size['size'] . 'px';
5158                  }
5159              }
5160              $theme_settings['settings']['typography']['fontSizes'] = $font_sizes;
5161          }
5162  
5163          if ( isset( $settings['enableCustomSpacing'] ) ) {
5164              $theme_settings['settings']['spacing']['padding'] = $settings['enableCustomSpacing'];
5165          }
5166  
5167          if ( isset( $settings['spacingSizes'] ) ) {
5168              $theme_settings['settings']['spacing']['spacingSizes'] = $settings['spacingSizes'];
5169          }
5170  
5171          return $theme_settings;
5172      }
5173  
5174      /**
5175       * Returns the current theme's wanted patterns(slugs) to be
5176       * registered from Pattern Directory.
5177       *
5178       * @since 6.0.0
5179       *
5180       * @return string[]
5181       */
5182  	public function get_patterns() {
5183          if ( isset( $this->theme_json['patterns'] ) && is_array( $this->theme_json['patterns'] ) ) {
5184              return $this->theme_json['patterns'];
5185          }
5186          return array();
5187      }
5188  
5189      /**
5190       * Returns a valid theme.json as provided by a theme.
5191       *
5192       * Unlike get_raw_data() this returns the presets flattened, as provided by a theme.
5193       * This also uses appearanceTools instead of their opt-ins if all of them are true.
5194       *
5195       * @since 6.0.0
5196       *
5197       * @return array
5198       */
5199  	public function get_data() {
5200          $output = $this->theme_json;
5201          $nodes  = static::get_setting_nodes( $output );
5202  
5203          /**
5204           * Flatten the theme & custom origins into a single one.
5205           *
5206           * For example, the following:
5207           *
5208           * {
5209           *   "settings": {
5210           *     "color": {
5211           *       "palette": {
5212           *         "theme": [ {} ],
5213           *         "custom": [ {} ]
5214           *       }
5215           *     }
5216           *   }
5217           * }
5218           *
5219           * will be converted to:
5220           *
5221           * {
5222           *   "settings": {
5223           *     "color": {
5224           *       "palette": [ {} ]
5225           *     }
5226           *   }
5227           * }
5228           */
5229          foreach ( $nodes as $node ) {
5230              foreach ( static::PRESETS_METADATA as $preset_metadata ) {
5231                  $path = $node['path'];
5232                  foreach ( $preset_metadata['path'] as $preset_metadata_path ) {
5233                      $path[] = $preset_metadata_path;
5234                  }
5235                  $preset = _wp_array_get( $output, $path, null );
5236                  if ( null === $preset ) {
5237                      continue;
5238                  }
5239  
5240                  $items = array();
5241                  if ( isset( $preset['theme'] ) ) {
5242                      foreach ( $preset['theme'] as $item ) {
5243                          $slug = $item['slug'];
5244                          unset( $item['slug'] );
5245                          $items[ $slug ] = $item;
5246                      }
5247                  }
5248                  if ( isset( $preset['custom'] ) ) {
5249                      foreach ( $preset['custom'] as $item ) {
5250                          $slug = $item['slug'];
5251                          unset( $item['slug'] );
5252                          $items[ $slug ] = $item;
5253                      }
5254                  }
5255                  $flattened_preset = array();
5256                  foreach ( $items as $slug => $value ) {
5257                      $flattened_preset[] = array_merge( array( 'slug' => (string) $slug ), $value );
5258                  }
5259                  _wp_array_set( $output, $path, $flattened_preset );
5260              }
5261          }
5262  
5263          /*
5264           * If all of the static::APPEARANCE_TOOLS_OPT_INS are true,
5265           * this code unsets them and sets 'appearanceTools' instead.
5266           */
5267          foreach ( $nodes as $node ) {
5268              $all_opt_ins_are_set = true;
5269              foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) {
5270                  $full_path = $node['path'];
5271                  foreach ( $opt_in_path as $opt_in_path_item ) {
5272                      $full_path[] = $opt_in_path_item;
5273                  }
5274                  /*
5275                   * Use "unset prop" as a marker instead of "null" because
5276                   * "null" can be a valid value for some props (e.g. blockGap).
5277                   */
5278                  $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' );
5279                  if ( 'unset prop' === $opt_in_value ) {
5280                      $all_opt_ins_are_set = false;
5281                      break;
5282                  }
5283              }
5284  
5285              if ( $all_opt_ins_are_set ) {
5286                  $node_path_with_appearance_tools   = $node['path'];
5287                  $node_path_with_appearance_tools[] = 'appearanceTools';
5288                  _wp_array_set( $output, $node_path_with_appearance_tools, true );
5289                  foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) {
5290                      $full_path = $node['path'];
5291                      foreach ( $opt_in_path as $opt_in_path_item ) {
5292                          $full_path[] = $opt_in_path_item;
5293                      }
5294                      /*
5295                       * Use "unset prop" as a marker instead of "null" because
5296                       * "null" can be a valid value for some props (e.g. blockGap).
5297                       */
5298                      $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' );
5299                      if ( true !== $opt_in_value ) {
5300                          continue;
5301                      }
5302  
5303                      /*
5304                       * The following could be improved to be path independent.
5305                       * At the moment it relies on a couple of assumptions:
5306                       *
5307                       * - all opt-ins having a path of size 2.
5308                       * - there's two sources of settings: the top-level and the block-level.
5309                       */
5310                      if (
5311                          ( 1 === count( $node['path'] ) ) &&
5312                          ( 'settings' === $node['path'][0] )
5313                      ) {
5314                          // Top-level settings.
5315                          unset( $output['settings'][ $opt_in_path[0] ][ $opt_in_path[1] ] );
5316                          if ( empty( $output['settings'][ $opt_in_path[0] ] ) ) {
5317                              unset( $output['settings'][ $opt_in_path[0] ] );
5318                          }
5319                      } elseif (
5320                          ( 3 === count( $node['path'] ) ) &&
5321                          ( 'settings' === $node['path'][0] ) &&
5322                          ( 'blocks' === $node['path'][1] )
5323                      ) {
5324                          // Block-level settings.
5325                          $block_name = $node['path'][2];
5326                          unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ][ $opt_in_path[1] ] );
5327                          if ( empty( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] ) ) {
5328                              unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] );
5329                          }
5330                      }
5331                  }
5332              }
5333          }
5334  
5335          wp_recursive_ksort( $output );
5336  
5337          return $output;
5338      }
5339  
5340      /**
5341       * Sets the spacingSizes array based on the spacingScale values from theme.json.
5342       *
5343       * @since 6.1.0
5344       * @deprecated 6.6.0 No longer used as the spacingSizes are automatically
5345       *                   generated in the constructor and merge methods instead
5346       *                   of manually after instantiation.
5347       *
5348       * @return void
5349       */
5350  	public function set_spacing_sizes() {
5351          _deprecated_function( __METHOD__, '6.6.0' );
5352  
5353          $spacing_scale = $this->theme_json['settings']['spacing']['spacingScale'] ?? array();
5354  
5355          if ( ! isset( $spacing_scale['steps'] )
5356              || ! is_numeric( $spacing_scale['steps'] )
5357              || ! isset( $spacing_scale['mediumStep'] )
5358              || ! isset( $spacing_scale['unit'] )
5359              || ! isset( $spacing_scale['operator'] )
5360              || ! isset( $spacing_scale['increment'] )
5361              || ! isset( $spacing_scale['steps'] )
5362              || ! is_numeric( $spacing_scale['increment'] )
5363              || ! is_numeric( $spacing_scale['mediumStep'] )
5364              || ( '+' !== $spacing_scale['operator'] && '*' !== $spacing_scale['operator'] ) ) {
5365              if ( ! empty( $spacing_scale ) ) {
5366                  wp_trigger_error(
5367                      __METHOD__,
5368                      sprintf(
5369                          /* translators: 1: theme.json, 2: settings.spacing.spacingScale */
5370                          __( 'Some of the %1$s %2$s values are invalid' ),
5371                          'theme.json',
5372                          'settings.spacing.spacingScale'
5373                      ),
5374                      E_USER_NOTICE
5375                  );
5376              }
5377              return;
5378          }
5379  
5380          // If theme authors want to prevent the generation of the core spacing scale they can set their theme.json spacingScale.steps to 0.
5381          if ( 0 === $spacing_scale['steps'] ) {
5382              return;
5383          }
5384  
5385          $spacing_sizes = static::compute_spacing_sizes( $spacing_scale );
5386  
5387          // If there are 7 or fewer steps in the scale revert to numbers for labels instead of t-shirt sizes.
5388          if ( $spacing_scale['steps'] <= 7 ) {
5389              for ( $spacing_sizes_count = 0, $spacing_sizes_length = count( $spacing_sizes ); $spacing_sizes_count < $spacing_sizes_length; $spacing_sizes_count++ ) {
5390                  $spacing_sizes[ $spacing_sizes_count ]['name'] = (string) ( $spacing_sizes_count + 1 );
5391              }
5392          }
5393  
5394          _wp_array_set( $this->theme_json, array( 'settings', 'spacing', 'spacingSizes', 'default' ), $spacing_sizes );
5395      }
5396  
5397      /**
5398       * Merges two sets of spacing size presets.
5399       *
5400       * @since 6.6.0
5401       *
5402       * @param array $base     The base set of spacing sizes.
5403       * @param array $incoming The set of spacing sizes to merge with the base. Duplicate slugs will override the base values.
5404       * @return array The merged set of spacing sizes.
5405       */
5406  	private static function merge_spacing_sizes( $base, $incoming ) {
5407          // Preserve the order if there are no base (spacingScale) values.
5408          if ( empty( $base ) ) {
5409              return $incoming;
5410          }
5411          $merged = array();
5412          foreach ( $base as $item ) {
5413              $merged[ $item['slug'] ] = $item;
5414          }
5415          foreach ( $incoming as $item ) {
5416              $merged[ $item['slug'] ] = $item;
5417          }
5418          ksort( $merged, SORT_NUMERIC );
5419          return array_values( $merged );
5420      }
5421  
5422      /**
5423       * Generates a set of spacing sizes by starting with a medium size and
5424       * applying an operator with an increment value to generate the rest of the
5425       * sizes outward from the medium size. The medium slug is '50' with the rest
5426       * of the slugs being 10 apart. The generated names use t-shirt sizing.
5427       *
5428       * Example:
5429       *
5430       *     $spacing_scale = array(
5431       *         'steps'      => 4,
5432       *         'mediumStep' => 16,
5433       *         'unit'       => 'px',
5434       *         'operator'   => '+',
5435       *         'increment'  => 2,
5436       *     );
5437       *     $spacing_sizes = static::compute_spacing_sizes( $spacing_scale );
5438       *     // -> array(
5439       *     //        array( 'name' => 'Small',   'slug' => '40', 'size' => '14px' ),
5440       *     //        array( 'name' => 'Medium',  'slug' => '50', 'size' => '16px' ),
5441       *     //        array( 'name' => 'Large',   'slug' => '60', 'size' => '18px' ),
5442       *     //        array( 'name' => 'X-Large', 'slug' => '70', 'size' => '20px' ),
5443       *     //    )
5444       *
5445       * @since 6.6.0
5446       *
5447       * @param array $spacing_scale {
5448       *      The spacing scale values. All are required.
5449       *
5450       *      @type int    $steps      The number of steps in the scale. (up to 10 steps are supported.)
5451       *      @type float  $mediumStep The middle value that gets the slug '50'. (For even number of steps, this becomes the first middle value.)
5452       *      @type string $unit       The CSS unit to use for the sizes.
5453       *      @type string $operator   The mathematical operator to apply to generate the other sizes. Either '+' or '*'.
5454       *      @type float  $increment  The value used with the operator to generate the other sizes.
5455       * }
5456       * @return array The spacing sizes presets or an empty array if some spacing scale values are missing or invalid.
5457       */
5458  	private static function compute_spacing_sizes( $spacing_scale ) {
5459          /*
5460           * This condition is intentionally missing some checks on ranges for the values in order to
5461           * keep backwards compatibility with the previous implementation.
5462           */
5463          if (
5464              ! isset( $spacing_scale['steps'] ) ||
5465              ! is_numeric( $spacing_scale['steps'] ) ||
5466              0 === $spacing_scale['steps'] ||
5467              ! isset( $spacing_scale['mediumStep'] ) ||
5468              ! is_numeric( $spacing_scale['mediumStep'] ) ||
5469              ! isset( $spacing_scale['unit'] ) ||
5470              ! isset( $spacing_scale['operator'] ) ||
5471              ( '+' !== $spacing_scale['operator'] && '*' !== $spacing_scale['operator'] ) ||
5472              ! isset( $spacing_scale['increment'] ) ||
5473              ! is_numeric( $spacing_scale['increment'] )
5474          ) {
5475              return array();
5476          }
5477  
5478          $unit            = '%' === $spacing_scale['unit'] ? '%' : sanitize_title( $spacing_scale['unit'] );
5479          $current_step    = $spacing_scale['mediumStep'];
5480          $steps_mid_point = round( $spacing_scale['steps'] / 2, 0 );
5481          $x_small_count   = null;
5482          $below_sizes     = array();
5483          $slug            = 40;
5484          $remainder       = 0;
5485  
5486          for ( $below_midpoint_count = $steps_mid_point - 1; $spacing_scale['steps'] > 1 && $slug > 0 && $below_midpoint_count > 0; $below_midpoint_count-- ) {
5487              if ( '+' === $spacing_scale['operator'] ) {
5488                  $current_step -= $spacing_scale['increment'];
5489              } elseif ( $spacing_scale['increment'] > 1 ) {
5490                  $current_step /= $spacing_scale['increment'];
5491              } else {
5492                  $current_step *= $spacing_scale['increment'];
5493              }
5494  
5495              if ( $current_step <= 0 ) {
5496                  $remainder = $below_midpoint_count;
5497                  break;
5498              }
5499  
5500              $below_sizes[] = array(
5501                  /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Small. */
5502                  'name' => $below_midpoint_count === $steps_mid_point - 1 ? __( 'Small' ) : sprintf( __( '%sX-Small' ), (string) $x_small_count ),
5503                  'slug' => (string) $slug,
5504                  'size' => round( $current_step, 2 ) . $unit,
5505              );
5506  
5507              if ( $below_midpoint_count === $steps_mid_point - 2 ) {
5508                  $x_small_count = 2;
5509              }
5510  
5511              if ( $below_midpoint_count < $steps_mid_point - 2 ) {
5512                  ++$x_small_count;
5513              }
5514  
5515              $slug -= 10;
5516          }
5517  
5518          $below_sizes = array_reverse( $below_sizes );
5519  
5520          $below_sizes[] = array(
5521              'name' => __( 'Medium' ),
5522              'slug' => '50',
5523              'size' => $spacing_scale['mediumStep'] . $unit,
5524          );
5525  
5526          $current_step  = $spacing_scale['mediumStep'];
5527          $x_large_count = null;
5528          $above_sizes   = array();
5529          $slug          = 60;
5530          $steps_above   = ( $spacing_scale['steps'] - $steps_mid_point ) + $remainder;
5531  
5532          for ( $above_midpoint_count = 0; $above_midpoint_count < $steps_above; $above_midpoint_count++ ) {
5533              $current_step = '+' === $spacing_scale['operator']
5534                  ? $current_step + $spacing_scale['increment']
5535                  : ( $spacing_scale['increment'] >= 1 ? $current_step * $spacing_scale['increment'] : $current_step / $spacing_scale['increment'] );
5536  
5537              $above_sizes[] = array(
5538                  /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Large. */
5539                  'name' => 0 === $above_midpoint_count ? __( 'Large' ) : sprintf( __( '%sX-Large' ), (string) $x_large_count ),
5540                  'slug' => (string) $slug,
5541                  'size' => round( $current_step, 2 ) . $unit,
5542              );
5543  
5544              if ( 1 === $above_midpoint_count ) {
5545                  $x_large_count = 2;
5546              }
5547  
5548              if ( $above_midpoint_count > 1 ) {
5549                  ++$x_large_count;
5550              }
5551  
5552              $slug += 10;
5553          }
5554  
5555          $spacing_sizes = $below_sizes;
5556          foreach ( $above_sizes as $above_sizes_item ) {
5557              $spacing_sizes[] = $above_sizes_item;
5558          }
5559  
5560          return $spacing_sizes;
5561      }
5562  
5563      /**
5564       * This is used to convert the internal representation of variables to the CSS representation.
5565       * For example, `var:preset|color|vivid-green-cyan` becomes `var(--wp--preset--color--vivid-green-cyan)`.
5566       *
5567       * @since 6.3.0
5568       *
5569       * @param string $value The variable such as var:preset|color|vivid-green-cyan to convert.
5570       * @return string The converted variable.
5571       */
5572  	private static function convert_custom_properties( $value ) {
5573          $prefix     = 'var:';
5574          $prefix_len = strlen( $prefix );
5575          $token_in   = '|';
5576          $token_out  = '--';
5577          if ( str_starts_with( $value, $prefix ) ) {
5578              $unwrapped_name = str_replace(
5579                  $token_in,
5580                  $token_out,
5581                  substr( $value, $prefix_len )
5582              );
5583              $value          = "var(--wp--$unwrapped_name)";
5584          }
5585  
5586          return $value;
5587      }
5588  
5589      /**
5590       * Given a tree, converts the internal representation of variables to the CSS representation.
5591       * It is recursive and modifies the input in-place.
5592       *
5593       * @since 6.3.0
5594       *
5595       * @param array $tree Input to process.
5596       * @return array The modified $tree.
5597       */
5598  	private static function resolve_custom_css_format( $tree ) {
5599          $prefix = 'var:';
5600  
5601          foreach ( $tree as $key => $data ) {
5602              if ( is_string( $data ) && str_starts_with( $data, $prefix ) ) {
5603                  $tree[ $key ] = self::convert_custom_properties( $data );
5604              } elseif ( is_array( $data ) ) {
5605                  $tree[ $key ] = self::resolve_custom_css_format( $data );
5606              }
5607          }
5608  
5609          return $tree;
5610      }
5611  
5612      /**
5613       * Returns the selectors metadata for a block.
5614       *
5615       * @since 6.3.0
5616       *
5617       * @param object $block_type    The block type.
5618       * @param string $root_selector The block's root selector.
5619       * @return array The custom selectors set by the block.
5620       */
5621  	protected static function get_block_selectors( $block_type, $root_selector ) {
5622          if ( ! empty( $block_type->selectors ) ) {
5623              return $block_type->selectors;
5624          }
5625  
5626          $selectors = array( 'root' => $root_selector );
5627          foreach ( static::BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS as $key => $feature ) {
5628              $feature_selector = wp_get_block_css_selector( $block_type, $key );
5629              if ( null !== $feature_selector ) {
5630                  $selectors[ $feature ] = array( 'root' => $feature_selector );
5631              }
5632          }
5633  
5634          return $selectors;
5635      }
5636  
5637      /**
5638       * Generates all the element selectors for a block.
5639       *
5640       * @since 6.3.0
5641       *
5642       * @param string $root_selector The block's root CSS selector.
5643       * @return array The block's element selectors.
5644       */
5645  	protected static function get_block_element_selectors( $root_selector ) {
5646          /*
5647           * Assign defaults, then override those that the block sets by itself.
5648           * If the block selector is compounded, will append the element to each
5649           * individual block selector.
5650           */
5651          $block_selectors   = explode( ',', $root_selector );
5652          $element_selectors = array();
5653          foreach ( static::ELEMENTS as $el_name => $el_selector ) {
5654              $element_selector = array();
5655              foreach ( $block_selectors as $selector ) {
5656                  if ( $selector === $el_selector ) {
5657                      $element_selector = array( $el_selector );
5658                      break;
5659                  }
5660                  $element_selector[] = static::prepend_to_selector( $el_selector, $selector . ' ' );
5661              }
5662              $element_selectors[ $el_name ] = implode( ',', $element_selector );
5663          }
5664  
5665          return $element_selectors;
5666      }
5667  
5668      /**
5669       * Generates style declarations for a node's features e.g., color, border,
5670       * typography etc. that have custom selectors in their related block's
5671       * metadata.
5672       *
5673       * @since 6.3.0
5674       *
5675       * @param object $metadata The related block metadata containing selectors.
5676       * @param object $node     A merged theme.json node for block or variation.
5677       * @return array The style declarations for the node's features with custom
5678       *               selectors.
5679       */
5680  	protected function get_feature_declarations_for_node( $metadata, &$node ) {
5681          $declarations = array();
5682  
5683          if ( ! isset( $metadata['selectors'] ) ) {
5684              return $declarations;
5685          }
5686  
5687          $settings = $this->theme_json['settings'] ?? array();
5688  
5689          foreach ( $metadata['selectors'] as $feature => $feature_selectors ) {
5690              /*
5691               * Skip if this is the block's root selector, the custom CSS
5692               * selector, or the block doesn't have any styles for the feature.
5693               */
5694              if ( 'root' === $feature || 'css' === $feature || empty( $node[ $feature ] ) ) {
5695                  continue;
5696              }
5697  
5698              if ( is_array( $feature_selectors ) ) {
5699                  foreach ( $feature_selectors as $subfeature => $subfeature_selector ) {
5700                      if ( 'root' === $subfeature || empty( $node[ $feature ][ $subfeature ] ) ) {
5701                          continue;
5702                      }
5703  
5704                      /*
5705                       * Create temporary node containing only the subfeature data
5706                       * to leverage existing `compute_style_properties` function.
5707                       */
5708                      $subfeature_node = array(
5709                          $feature => array(
5710                              $subfeature => $node[ $feature ][ $subfeature ],
5711                          ),
5712                      );
5713  
5714                      // Generate style declarations.
5715                      $new_declarations = static::compute_style_properties( $subfeature_node, $settings, null, $this->theme_json );
5716  
5717                      // Merge subfeature declarations into feature declarations.
5718                      if ( isset( $declarations[ $subfeature_selector ] ) ) {
5719                          foreach ( $new_declarations as $new_declaration ) {
5720                              $declarations[ $subfeature_selector ][] = $new_declaration;
5721                          }
5722                      } else {
5723                          $declarations[ $subfeature_selector ] = $new_declarations;
5724                      }
5725  
5726                      /*
5727                       * Remove the subfeature from the block's node now its
5728                       * styles will be included under its own selector not the
5729                       * block's.
5730                       */
5731                      unset( $node[ $feature ][ $subfeature ] );
5732                  }
5733              }
5734  
5735              /*
5736               * Now subfeatures have been processed and removed we can process
5737               * feature root selector or simple string selector.
5738               */
5739              if (
5740                  is_string( $feature_selectors ) ||
5741                  ( isset( $feature_selectors['root'] ) && $feature_selectors['root'] )
5742              ) {
5743                  $feature_selector = is_string( $feature_selectors ) ? $feature_selectors : $feature_selectors['root'];
5744  
5745                  /*
5746                   * Create temporary node containing only the feature data
5747                   * to leverage existing `compute_style_properties` function.
5748                   */
5749                  $feature_node = array( $feature => $node[ $feature ] );
5750  
5751                  // Generate the style declarations.
5752                  $new_declarations = static::compute_style_properties( $feature_node, $settings, null, $this->theme_json );
5753  
5754                  /*
5755                   * Merge new declarations with any that already exist for
5756                   * the feature selector. This may occur when multiple block
5757                   * support features use the same custom selector.
5758                   */
5759                  if ( isset( $declarations[ $feature_selector ] ) ) {
5760                      foreach ( $new_declarations as $new_declaration ) {
5761                          $declarations[ $feature_selector ][] = $new_declaration;
5762                      }
5763                  } else {
5764                      $declarations[ $feature_selector ] = $new_declarations;
5765                  }
5766  
5767                  /*
5768                   * Remove the feature from the block's node now its styles
5769                   * will be included under its own selector not the block's.
5770                   */
5771                  unset( $node[ $feature ] );
5772              }
5773          }
5774  
5775          return $declarations;
5776      }
5777  
5778      /**
5779       * Replaces CSS variables with their values in place.
5780       *
5781       * @since 6.3.0
5782       * @since 6.5.0 Check for empty style before processing its value.
5783       *
5784       * @param array $styles CSS declarations to convert.
5785       * @param array $values key => value pairs to use for replacement.
5786       * @return array
5787       */
5788  	private static function convert_variables_to_value( $styles, $values ) {
5789          foreach ( $styles as $key => $style ) {
5790              if ( empty( $style ) ) {
5791                  continue;
5792              }
5793  
5794              if ( is_array( $style ) ) {
5795                  $styles[ $key ] = self::convert_variables_to_value( $style, $values );
5796                  continue;
5797              }
5798  
5799              if ( 0 <= strpos( $style, 'var(' ) ) {
5800                  // find all the variables in the string in the form of var(--variable-name, fallback), with fallback in the second capture group.
5801  
5802                  $has_matches = preg_match_all( '/var\(([^),]+)?,?\s?(\S+)?\)/', $style, $var_parts );
5803  
5804                  if ( $has_matches ) {
5805                      $resolved_style = $styles[ $key ];
5806                      foreach ( $var_parts[1] as $index => $var_part ) {
5807                          $key_in_values   = 'var(' . $var_part . ')';
5808                          $rule_to_replace = $var_parts[0][ $index ]; // the css rule to replace e.g. var(--wp--preset--color--vivid-green-cyan).
5809                          $fallback        = $var_parts[2][ $index ]; // the fallback value.
5810                          $resolved_style  = str_replace(
5811                              array(
5812                                  $rule_to_replace,
5813                                  $fallback,
5814                              ),
5815                              array(
5816                                  $values[ $key_in_values ] ?? $rule_to_replace,
5817                                  $values[ $fallback ] ?? $fallback,
5818                              ),
5819                              $resolved_style
5820                          );
5821                      }
5822                      $styles[ $key ] = $resolved_style;
5823                  }
5824              }
5825          }
5826  
5827          return $styles;
5828      }
5829  
5830      /**
5831       * Resolves the values of CSS variables in the given styles.
5832       *
5833       * @since 6.3.0
5834       *
5835       * @param WP_Theme_JSON $theme_json The theme json resolver.
5836       * @return WP_Theme_JSON The $theme_json with resolved variables.
5837       */
5838  	public static function resolve_variables( $theme_json ) {
5839          $settings    = $theme_json->get_settings();
5840          $styles      = $theme_json->get_raw_data()['styles'];
5841          $preset_vars = static::compute_preset_vars( $settings, static::VALID_ORIGINS );
5842          $theme_vars  = static::compute_theme_vars( $settings );
5843          $vars        = array_reduce(
5844              array_merge( $preset_vars, $theme_vars ),
5845              function ( $carry, $item ) {
5846                  $name                    = $item['name'];
5847                  $carry[ "var({$name})" ] = $item['value'];
5848                  return $carry;
5849              },
5850              array()
5851          );
5852  
5853          $theme_json->theme_json['styles'] = self::convert_variables_to_value( $styles, $vars );
5854          return $theme_json;
5855      }
5856  
5857      /**
5858       * Generates a selector for a block style variation.
5859       *
5860       * @since 6.5.0
5861       *
5862       * @param string $variation_name Name of the block style variation.
5863       * @param string $block_selector CSS selector for the block.
5864       * @return string Block selector with block style variation selector added to it.
5865       */
5866  	protected static function get_block_style_variation_selector( $variation_name, $block_selector ) {
5867          $variation_class = ".is-style-$variation_name";
5868  
5869          if ( ! $block_selector ) {
5870              return $variation_class;
5871          }
5872  
5873          $limit          = 1;
5874          $selector_parts = static::split_selector_list( $block_selector );
5875          $result         = array();
5876  
5877          /*
5878           * Append the variation class to each selector's ancestor: the first
5879           * run of characters before any combinator (whitespace) or pseudo-class
5880           * (`:`). Only the first match is replaced.
5881           *
5882           * Examples ("custom" variation):
5883           * - `.wp-block`              => `.wp-block.is-style-custom`
5884           * - `.wp-block .inner`       => `.wp-block.is-style-custom .inner`
5885           * - `.wp-block:where(.a .b)` => `.wp-block.is-style-custom:where(.a .b)`
5886           * - `:where(.outer .inner)`  => `:where(.outer.is-style-custom .inner)`
5887           */
5888          foreach ( $selector_parts as $part ) {
5889              $result[] = preg_replace_callback(
5890                  '/[^\s:]+/',
5891                  function ( $matches ) use ( $variation_class ) {
5892                      return $matches[0] . $variation_class;
5893                  },
5894                  $part,
5895                  $limit
5896              );
5897          }
5898  
5899          return implode( ', ', $result );
5900      }
5901  
5902      /**
5903       * Applies a block style variation class to a feature selector.
5904       *
5905       * Feature selectors can target a different element than the block's root
5906       * selector. For example, the Button block's root selector targets the inner
5907       * link, while its dimensions width selector targets the outer wrapper. Apply
5908       * the variation class directly to the selector that will receive the
5909       * declarations instead of deriving it by subtracting the root selector from
5910       * the feature selector.
5911       *
5912       * @since 7.0.0
5913       *
5914       * @param array  $style_variation Style variation metadata.
5915       * @param string $feature_selector CSS selector for the feature.
5916       * @return string Feature selector with block style variation selector added.
5917       */
5918  	protected static function get_block_style_variation_feature_selector( $style_variation, $feature_selector ) {
5919          $variation_path = $style_variation['path'] ?? array();
5920          $variation_name = $style_variation['name'] ?? ( is_array( $variation_path ) ? end( $variation_path ) : null );
5921  
5922          if ( ! $variation_name ) {
5923              return $style_variation['selector'] ?? $feature_selector;
5924          }
5925  
5926          $variation_class = ".is-style-$variation_name";
5927          $selector_parts  = static::split_selector_list( $feature_selector );
5928          $selector_parts  = array_map(
5929              static function ( $selector ) use ( $variation_class ) {
5930                  $prefix = $variation_class . ' ';
5931  
5932                  if ( str_starts_with( $selector, $prefix ) ) {
5933                      return substr( $selector, strlen( $prefix ) );
5934                  }
5935  
5936                  return $selector;
5937              },
5938              $selector_parts
5939          );
5940  
5941          return static::get_block_style_variation_selector(
5942              $variation_name,
5943              implode( ', ', $selector_parts )
5944          );
5945      }
5946  
5947      /**
5948       * Collects valid block style variations keyed by block type.
5949       *
5950       * @since 6.6.0
5951       * @since 6.8.0 Added the `$blocks_metadata` parameter.
5952       *
5953       * @param array $blocks_metadata Optional. List of metadata per block. Default is the metadata for all blocks.
5954       * @return array Valid block style variations by block type.
5955       */
5956  	protected static function get_valid_block_style_variations( $blocks_metadata = array() ) {
5957          $valid_variations = array();
5958          $blocks_metadata  = empty( $blocks_metadata ) ? static::get_blocks_metadata() : $blocks_metadata;
5959          foreach ( $blocks_metadata as $block_name => $block_meta ) {
5960              if ( ! isset( $block_meta['styleVariations'] ) ) {
5961                  continue;
5962              }
5963              $valid_variations[ $block_name ] = array_keys( $block_meta['styleVariations'] );
5964          }
5965  
5966          return $valid_variations;
5967      }
5968  
5969      /**
5970       * Extracts the block name from the block metadata path.
5971       *
5972       * @since 7.1.0
5973       *
5974       * @param array $block_metadata Block metadata.
5975       * @return string|null The block name or null if not found.
5976       */
5977  	private static function get_block_name_from_metadata_path( $block_metadata ) {
5978          return $block_metadata['path'][2] ?? null;
5979      }
5980  }


Generated : Fri Aug 14 08:20:23 2026 Cross-referenced by PHPXref