[ 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       *   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       *
2617       * @param array    $settings Settings to process.
2618       * @param string   $selector Selector wrapping the classes.
2619       * @param string[] $origins  List of origins to process.
2620       * @return string The result of processing the presets.
2621       */
2622  	protected static function compute_preset_classes( $settings, $selector, $origins ) {
2623          if ( static::ROOT_BLOCK_SELECTOR === $selector || static::ROOT_CSS_PROPERTIES_SELECTOR === $selector ) {
2624              /*
2625               * Classes at the global level do not need any CSS prefixed,
2626               * and we don't want to increase its specificity.
2627               */
2628              $selector = '';
2629          }
2630  
2631          $stylesheet = '';
2632          foreach ( static::PRESETS_METADATA as $preset_metadata ) {
2633              if ( empty( $preset_metadata['classes'] ) ) {
2634                  continue;
2635              }
2636              $slugs = static::get_settings_slugs( $settings, $preset_metadata, $origins );
2637              foreach ( $preset_metadata['classes'] as $class => $property ) {
2638                  foreach ( $slugs as $slug ) {
2639                      $css_var    = static::replace_slug_in_string( $preset_metadata['css_vars'], $slug );
2640                      $class_name = static::replace_slug_in_string( $class, $slug );
2641  
2642                      // $selector is often empty, so we can save ourselves the `append_to_selector()` call then.
2643                      $new_selector = '' === $selector ? $class_name : static::append_to_selector( $selector, $class_name );
2644                      $stylesheet  .= static::to_ruleset(
2645                          $new_selector,
2646                          array(
2647                              array(
2648                                  'name'  => $property,
2649                                  'value' => 'var(' . $css_var . ') !important',
2650                              ),
2651                          )
2652                      );
2653                  }
2654              }
2655          }
2656  
2657          return $stylesheet;
2658      }
2659  
2660      /**
2661       * Function that scopes a selector with another one. This works a bit like
2662       * SCSS nesting except the `&` operator isn't supported.
2663       *
2664       * <code>
2665       * $scope = '.a, .b .c';
2666       * $selector = '> .x, .y';
2667       * $merged = scope_selector( $scope, $selector );
2668       * // $merged is '.a > .x, .a .y, .b .c > .x, .b .c .y'
2669       * </code>
2670       *
2671       * @since 5.9.0
2672       * @since 6.6.0 Added early return if missing scope or selector.
2673       *
2674       * @param string $scope    Selector to scope to.
2675       * @param string $selector Original selector.
2676       * @return string Scoped selector.
2677       */
2678  	public static function scope_selector( $scope, $selector ) {
2679          if ( ! $scope || ! $selector ) {
2680              return $selector;
2681          }
2682  
2683          $scopes    = static::split_selector_list( $scope );
2684          $selectors = static::split_selector_list( $selector );
2685  
2686          $selectors_scoped = array();
2687          foreach ( $scopes as $outer ) {
2688              foreach ( $selectors as $inner ) {
2689                  if ( ! empty( $outer ) && ! empty( $inner ) ) {
2690                      $selectors_scoped[] = $outer . ' ' . $inner;
2691                  } elseif ( empty( $outer ) ) {
2692                      $selectors_scoped[] = $inner;
2693                  } elseif ( empty( $inner ) ) {
2694                      $selectors_scoped[] = $outer;
2695                  }
2696              }
2697          }
2698  
2699          $result = implode( ', ', $selectors_scoped );
2700          return $result;
2701      }
2702  
2703      /**
2704       * Scopes the selectors for a given style node.
2705       *
2706       * This includes the primary selector, i.e. `$node['selector']`, as well as any custom
2707       * selectors for features and subfeatures, e.g. `$node['selectors']['border']` etc.
2708       *
2709       * @since 6.6.0
2710       *
2711       * @param string $scope Selector to scope to.
2712       * @param array  $node  Style node with selectors to scope.
2713       * @return array Node with updated selectors.
2714       */
2715  	protected static function scope_style_node_selectors( $scope, $node ) {
2716          $node['selector'] = static::scope_selector( $scope, $node['selector'] );
2717  
2718          if ( empty( $node['selectors'] ) ) {
2719              return $node;
2720          }
2721  
2722          foreach ( $node['selectors'] as $feature => $selector ) {
2723              if ( is_string( $selector ) ) {
2724                  $node['selectors'][ $feature ] = static::scope_selector( $scope, $selector );
2725              }
2726              if ( is_array( $selector ) ) {
2727                  foreach ( $selector as $subfeature => $subfeature_selector ) {
2728                      $node['selectors'][ $feature ][ $subfeature ] = static::scope_selector( $scope, $subfeature_selector );
2729                  }
2730              }
2731          }
2732  
2733          return $node;
2734      }
2735  
2736      /**
2737       * Gets preset values keyed by slugs based on settings and metadata.
2738       *
2739       * <code>
2740       * $settings = array(
2741       *     'typography' => array(
2742       *         'fontFamilies' => array(
2743       *             array(
2744       *                 'slug'       => 'sansSerif',
2745       *                 'fontFamily' => '"Helvetica Neue", sans-serif',
2746       *             ),
2747       *             array(
2748       *                 'slug'   => 'serif',
2749       *                 'colors' => 'Georgia, serif',
2750       *             )
2751       *         ),
2752       *     ),
2753       * );
2754       * $meta = array(
2755       *    'path'      => array( 'typography', 'fontFamilies' ),
2756       *    'value_key' => 'fontFamily',
2757       * );
2758       * $values_by_slug = get_settings_values_by_slug();
2759       * // $values_by_slug === array(
2760       * //   'sans-serif' => '"Helvetica Neue", sans-serif',
2761       * //   'serif'      => 'Georgia, serif',
2762       * // );
2763       * </code>
2764       *
2765       * @since 5.9.0
2766       * @since 6.6.0 Passing $settings to the callbacks defined in static::PRESETS_METADATA.
2767       *
2768       * @param array    $settings        Settings to process.
2769       * @param array    $preset_metadata One of the PRESETS_METADATA values.
2770       * @param string[] $origins         List of origins to process.
2771       * @return array Array of presets where each key is a slug and each value is the preset value.
2772       */
2773  	protected static function get_settings_values_by_slug( $settings, $preset_metadata, $origins ) {
2774          $preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() );
2775  
2776          $result = array();
2777          foreach ( $origins as $origin ) {
2778              if ( ! isset( $preset_per_origin[ $origin ] ) ) {
2779                  continue;
2780              }
2781              foreach ( $preset_per_origin[ $origin ] as $preset ) {
2782                  $slug = _wp_to_kebab_case( $preset['slug'] );
2783  
2784                  $value = '';
2785                  if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) {
2786                      $value_key = $preset_metadata['value_key'];
2787                      $value     = $preset[ $value_key ];
2788                  } elseif (
2789                      isset( $preset_metadata['value_func'] ) &&
2790                      is_callable( $preset_metadata['value_func'] )
2791                  ) {
2792                      $value_func = $preset_metadata['value_func'];
2793                      $value      = call_user_func( $value_func, $preset, $settings );
2794                  } else {
2795                      // If we don't have a value, then don't add it to the result.
2796                      continue;
2797                  }
2798  
2799                  $result[ $slug ] = $value;
2800              }
2801          }
2802          return $result;
2803      }
2804  
2805      /**
2806       * Similar to get_settings_values_by_slug, but doesn't compute the value.
2807       *
2808       * @since 5.9.0
2809       *
2810       * @param array    $settings        Settings to process.
2811       * @param array    $preset_metadata One of the PRESETS_METADATA values.
2812       * @param string[] $origins         List of origins to process.
2813       * @return array Array of presets where the key and value are both the slug.
2814       */
2815  	protected static function get_settings_slugs( $settings, $preset_metadata, $origins = null ) {
2816          if ( null === $origins ) {
2817              $origins = static::VALID_ORIGINS;
2818          }
2819  
2820          $preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() );
2821  
2822          $result = array();
2823          foreach ( $origins as $origin ) {
2824              if ( ! isset( $preset_per_origin[ $origin ] ) ) {
2825                  continue;
2826              }
2827              foreach ( $preset_per_origin[ $origin ] as $preset ) {
2828                  $slug = _wp_to_kebab_case( $preset['slug'] );
2829  
2830                  // Use the array as a set so we don't get duplicates.
2831                  $result[ $slug ] = $slug;
2832              }
2833          }
2834          return $result;
2835      }
2836  
2837      /**
2838       * Transforms a slug into a CSS Custom Property.
2839       *
2840       * @since 5.9.0
2841       *
2842       * @param string $input String to replace.
2843       * @param string $slug  The slug value to use to generate the custom property.
2844       * @return string The CSS Custom Property. Something along the lines of `--wp--preset--color--black`.
2845       */
2846  	protected static function replace_slug_in_string( $input, $slug ) {
2847          return strtr( $input, array( '$slug' => $slug ) );
2848      }
2849  
2850      /**
2851       * Given the block settings, extracts the CSS Custom Properties
2852       * for the presets and adds them to the $declarations array
2853       * following the format:
2854       *
2855       *     array(
2856       *       'name'  => 'property_name',
2857       *       'value' => 'property_value,
2858       *     )
2859       *
2860       * @since 5.8.0
2861       * @since 5.9.0 Added the `$origins` parameter.
2862       *
2863       * @param array    $settings Settings to process.
2864       * @param string[] $origins  List of origins to process.
2865       * @return array The modified $declarations.
2866       */
2867  	protected static function compute_preset_vars( $settings, $origins ) {
2868          $declarations = array();
2869          foreach ( static::PRESETS_METADATA as $preset_metadata ) {
2870              if ( empty( $preset_metadata['css_vars'] ) ) {
2871                  continue;
2872              }
2873              $values_by_slug = static::get_settings_values_by_slug( $settings, $preset_metadata, $origins );
2874              foreach ( $values_by_slug as $slug => $value ) {
2875                  $declarations[] = array(
2876                      'name'  => static::replace_slug_in_string( $preset_metadata['css_vars'], $slug ),
2877                      'value' => $value,
2878                  );
2879              }
2880          }
2881  
2882          return $declarations;
2883      }
2884  
2885      /**
2886       * Given an array of settings, extracts the CSS Custom Properties
2887       * for the custom values and adds them to the $declarations
2888       * array following the format:
2889       *
2890       *     array(
2891       *       'name'  => 'property_name',
2892       *       'value' => 'property_value,
2893       *     )
2894       *
2895       * @since 5.8.0
2896       *
2897       * @param array $settings Settings to process.
2898       * @return array The modified $declarations.
2899       */
2900  	protected static function compute_theme_vars( $settings ) {
2901          $declarations  = array();
2902          $custom_values = $settings['custom'] ?? array();
2903          $css_vars      = static::flatten_tree( $custom_values );
2904          foreach ( $css_vars as $key => $value ) {
2905              $declarations[] = array(
2906                  'name'  => '--wp--custom--' . $key,
2907                  'value' => $value,
2908              );
2909          }
2910  
2911          return $declarations;
2912      }
2913  
2914      /**
2915       * Given a tree, it creates a flattened one
2916       * by merging the keys and binding the leaf values
2917       * to the new keys.
2918       *
2919       * It also transforms camelCase names into kebab-case
2920       * and substitutes '/' by '-'.
2921       *
2922       * This is thought to be useful to generate
2923       * CSS Custom Properties from a tree,
2924       * although there's nothing in the implementation
2925       * of this function that requires that format.
2926       *
2927       * For example, assuming the given prefix is '--wp'
2928       * and the token is '--', for this input tree:
2929       *
2930       *     {
2931       *       'some/property': 'value',
2932       *       'nestedProperty': {
2933       *         'sub-property': 'value'
2934       *       }
2935       *     }
2936       *
2937       * it'll return this output:
2938       *
2939       *     {
2940       *       '--wp--some-property': 'value',
2941       *       '--wp--nested-property--sub-property': 'value'
2942       *     }
2943       *
2944       * @since 5.8.0
2945       *
2946       * @param array  $tree   Input tree to process.
2947       * @param string $prefix Optional. Prefix to prepend to each variable. Default empty string.
2948       * @param string $token  Optional. Token to use between levels. Default '--'.
2949       * @return array The flattened tree.
2950       */
2951  	protected static function flatten_tree( $tree, $prefix = '', $token = '--' ) {
2952          $result = array();
2953          foreach ( $tree as $property => $value ) {
2954              $new_key = $prefix . str_replace(
2955                  '/',
2956                  '-',
2957                  strtolower( _wp_to_kebab_case( $property ) )
2958              );
2959  
2960              if ( is_array( $value ) ) {
2961                  $new_prefix        = $new_key . $token;
2962                  $flattened_subtree = static::flatten_tree( $value, $new_prefix, $token );
2963                  foreach ( $flattened_subtree as $subtree_key => $subtree_value ) {
2964                      $result[ $subtree_key ] = $subtree_value;
2965                  }
2966              } else {
2967                  $result[ $new_key ] = $value;
2968              }
2969          }
2970          return $result;
2971      }
2972  
2973      /**
2974       * Given a styles array, it extracts the style properties
2975       * and adds them to the $declarations array following the format:
2976       *
2977       *     array(
2978       *       'name'  => 'property_name',
2979       *       'value' => 'property_value',
2980       *     )
2981       *
2982       * @since 5.8.0
2983       * @since 5.9.0 Added the `$settings` and `$properties` parameters.
2984       * @since 6.1.0 Added `$theme_json`, `$selector`, and `$use_root_padding` parameters.
2985       * @since 6.5.0 Output a `min-height: unset` rule when `aspect-ratio` is set.
2986       * @since 6.6.0 Pass current theme JSON settings to wp_get_typography_font_size_value(), and process background properties.
2987       * @since 6.7.0 `ref` resolution of background properties, and assigning custom default values.
2988       *
2989       * @param array   $styles Styles to process.
2990       * @param array   $settings Theme settings.
2991       * @param array   $properties Properties metadata.
2992       * @param array   $theme_json Theme JSON array.
2993       * @param string  $selector The style block selector.
2994       * @param boolean $use_root_padding Whether to add custom properties at root level.
2995       * @return array Returns the modified $declarations.
2996       */
2997  	protected static function compute_style_properties( $styles, $settings = array(), $properties = null, $theme_json = null, $selector = null, $use_root_padding = null ) {
2998          if ( empty( $styles ) ) {
2999              return array();
3000          }
3001  
3002          if ( null === $properties ) {
3003              $properties = static::PROPERTIES_METADATA;
3004          }
3005          $declarations             = array();
3006          $root_variable_duplicates = array();
3007          $root_style_length        = strlen( '--wp--style--root--' );
3008  
3009          foreach ( $properties as $css_property => $value_path ) {
3010              if ( ! is_array( $value_path ) ) {
3011                  continue;
3012              }
3013  
3014              $is_root_style = str_starts_with( $css_property, '--wp--style--root--' );
3015              if ( $is_root_style && ( static::ROOT_BLOCK_SELECTOR !== $selector || ! $use_root_padding ) ) {
3016                  continue;
3017              }
3018  
3019              $value = static::get_property_value( $styles, $value_path, $theme_json );
3020  
3021              /*
3022               * Root-level padding styles don't currently support strings with CSS shorthand values.
3023               * This may change: https://github.com/WordPress/gutenberg/issues/40132.
3024               */
3025              if ( '--wp--style--root--padding' === $css_property && is_string( $value ) ) {
3026                  continue;
3027              }
3028  
3029              if ( $is_root_style && $use_root_padding ) {
3030                  $root_variable_duplicates[] = substr( $css_property, $root_style_length );
3031              }
3032  
3033              /*
3034               * Processes background image styles.
3035               * If the value is a URL, it will be converted to a CSS `url()` value.
3036               * For uploaded image (images with a database ID), apply size and position defaults,
3037               * equal to those applied in block supports in lib/background.php.
3038               */
3039              if ( 'background-image' === $css_property ) {
3040                  $background_image_input = array();
3041                  if ( ! empty( $value ) ) {
3042                      $background_image_input['backgroundImage'] = $value;
3043                  }
3044                  $gradient_value = $styles['background']['gradient'] ?? null;
3045                  if ( ! empty( $gradient_value ) ) {
3046                      $background_image_input['gradient'] = $gradient_value;
3047                  }
3048                  if ( ! empty( $background_image_input ) ) {
3049                      $background_styles = wp_style_engine_get_styles(
3050                          array( 'background' => $background_image_input )
3051                      );
3052                      $value             = $background_styles['declarations'][ $css_property ] ?? null;
3053                  }
3054              }
3055              if ( empty( $value ) && static::ROOT_BLOCK_SELECTOR !== $selector && ! empty( $styles['background']['backgroundImage']['id'] ) ) {
3056                  if ( 'background-size' === $css_property ) {
3057                      $value = 'cover';
3058                  }
3059                  // If the background size is set to `contain` and no position is set, set the position to `center`.
3060                  if ( 'background-position' === $css_property ) {
3061                      $background_size = $styles['background']['backgroundSize'] ?? null;
3062                      $value           = 'contain' === $background_size ? '50% 50%' : null;
3063                  }
3064              }
3065  
3066              // Skip if empty and not "0" or value represents array of longhand values.
3067              $has_missing_value = empty( $value ) && ! is_numeric( $value );
3068              if ( $has_missing_value || is_array( $value ) ) {
3069                  continue;
3070              }
3071  
3072              // Calculates fluid typography rules where available.
3073              if ( 'font-size' === $css_property ) {
3074                  /*
3075                   * wp_get_typography_font_size_value() will check
3076                   * if fluid typography has been activated and also
3077                   * whether the incoming value can be converted to a fluid value.
3078                   * Values that already have a clamp() function will not pass the test,
3079                   * and therefore the original $value will be returned.
3080                   * Pass the current theme_json settings to override any global settings.
3081                   */
3082                  $value = wp_get_typography_font_size_value( array( 'size' => $value ), $settings );
3083              }
3084  
3085              if ( 'aspect-ratio' === $css_property ) {
3086                  // For aspect ratio to work, other dimensions rules must be unset.
3087                  // This ensures that a fixed height does not override the aspect ratio.
3088                  $declarations[] = array(
3089                      'name'  => 'min-height',
3090                      'value' => 'unset',
3091                  );
3092              }
3093  
3094              $declarations[] = array(
3095                  'name'  => $css_property,
3096                  'value' => $value,
3097              );
3098          }
3099  
3100          // If a variable value is added to the root, the corresponding property should be removed.
3101          foreach ( $root_variable_duplicates as $duplicate ) {
3102              $discard = array_search( $duplicate, array_column( $declarations, 'name' ), true );
3103              if ( is_numeric( $discard ) ) {
3104                  array_splice( $declarations, $discard, 1 );
3105              }
3106          }
3107  
3108          return $declarations;
3109      }
3110  
3111      /**
3112       * Returns the style property for the given path.
3113       *
3114       * It also converts references to a path to the value
3115       * stored at that location, e.g.
3116       * { "ref": "style.color.background" } => "#fff".
3117       *
3118       * @since 5.8.0
3119       * @since 5.9.0 Added support for values of array type, which are returned as is.
3120       * @since 6.1.0 Added the `$theme_json` parameter.
3121       * @since 6.3.0 It no longer converts the internal format "var:preset|color|secondary"
3122       *              to the standard form "--wp--preset--color--secondary".
3123       *              This is already done by the sanitize method,
3124       *              so every property will be in the standard form.
3125       * @since 6.7.0 Added support for background image refs.
3126       *
3127       * @param array $styles Styles subtree.
3128       * @param array $path   Which property to process.
3129       * @param array $theme_json Theme JSON array.
3130       * @return string|array Style property value.
3131       */
3132  	protected static function get_property_value( $styles, $path, $theme_json = null ) {
3133          $value = _wp_array_get( $styles, $path, '' );
3134  
3135          if ( '' === $value || null === $value ) {
3136              // No need to process the value further.
3137              return '';
3138          }
3139  
3140          /*
3141           * This converts references to a path to the value at that path
3142           * where the value is an array with a "ref" key, pointing to a path.
3143           * For example: { "ref": "style.color.background" } => "#fff".
3144           * In the case of backgroundImage, if both a ref and a URL are present in the value,
3145           * the URL takes precedence and the ref is ignored.
3146           */
3147          if ( is_array( $value ) && isset( $value['ref'] ) ) {
3148              $value_path = explode( '.', $value['ref'] );
3149              $ref_value  = _wp_array_get( $theme_json, $value_path );
3150              // Background Image refs can refer to a string or an array containing a URL string.
3151              $ref_value_url = $ref_value['url'] ?? null;
3152              // Only use the ref value if we find anything.
3153              if ( ! empty( $ref_value ) && ( is_string( $ref_value ) || is_string( $ref_value_url ) ) ) {
3154                  $value = $ref_value;
3155              }
3156  
3157              if ( is_array( $ref_value ) && isset( $ref_value['ref'] ) ) {
3158                  $path_string      = json_encode( $path );
3159                  $ref_value_string = json_encode( $ref_value );
3160                  _doing_it_wrong(
3161                      'get_property_value',
3162                      sprintf(
3163                          /* translators: 1: theme.json, 2: Value name, 3: Value path, 4: Another value name. */
3164                          __( '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.' ),
3165                          'theme.json',
3166                          $ref_value_string,
3167                          $path_string,
3168                          $ref_value['ref']
3169                      ),
3170                      '6.1.0'
3171                  );
3172              }
3173          }
3174  
3175          return $value;
3176      }
3177  
3178      /**
3179       * Builds metadata for the setting nodes, which returns in the form of:
3180       *
3181       *     [
3182       *       [
3183       *         'path'     => ['path', 'to', 'some', 'node' ],
3184       *         'selector' => 'CSS selector for some node'
3185       *       ],
3186       *       [
3187       *         'path'     => [ 'path', 'to', 'other', 'node' ],
3188       *         'selector' => 'CSS selector for other node'
3189       *       ],
3190       *     ]
3191       *
3192       * @since 5.8.0
3193       *
3194       * @param array $theme_json The tree to extract setting nodes from.
3195       * @param array $selectors  List of selectors per block.
3196       * @return array An array of setting nodes metadata.
3197       */
3198  	protected static function get_setting_nodes( $theme_json, $selectors = array() ) {
3199          $nodes = array();
3200          if ( ! isset( $theme_json['settings'] ) ) {
3201              return $nodes;
3202          }
3203  
3204          // Top-level.
3205          $nodes[] = array(
3206              'path'     => array( 'settings' ),
3207              'selector' => static::ROOT_CSS_PROPERTIES_SELECTOR,
3208          );
3209  
3210          // Calculate paths for blocks.
3211          if ( ! isset( $theme_json['settings']['blocks'] ) ) {
3212              return $nodes;
3213          }
3214  
3215          foreach ( $theme_json['settings']['blocks'] as $name => $node ) {
3216              $selector = null;
3217              if ( isset( $selectors[ $name ]['selector'] ) ) {
3218                  $selector = $selectors[ $name ]['selector'];
3219              }
3220  
3221              $nodes[] = array(
3222                  'path'      => array( 'settings', 'blocks', $name ),
3223                  'selector'  => $selector,
3224                  'selectors' => $selectors[ $name ]['selectors'] ?? array(),
3225              );
3226          }
3227  
3228          return $nodes;
3229      }
3230  
3231      /**
3232       * Builds metadata for the style nodes, which returns in the form of:
3233       *
3234       *     [
3235       *       [
3236       *         'path'     => [ 'path', 'to', 'some', 'node' ],
3237       *         'selector' => 'CSS selector for some node',
3238       *         'duotone'  => 'CSS selector for duotone for some node'
3239       *       ],
3240       *       [
3241       *         'path'     => ['path', 'to', 'other', 'node' ],
3242       *         'selector' => 'CSS selector for other node',
3243       *         'duotone'  => null
3244       *       ],
3245       *     ]
3246       *
3247       * @since 5.8.0
3248       * @since 6.6.0 Added options array for modifying generated nodes.
3249       *
3250       * @param array $theme_json The tree to extract style nodes from.
3251       * @param array $selectors  List of selectors per block.
3252       * @param array $options {
3253       *     Optional. An array of options for now used for internal purposes only (may change without notice).
3254       *
3255       *     @type bool $include_block_style_variations Includes style nodes for block style variations. Default false.
3256       * }
3257       * @return array An array of style nodes metadata.
3258       */
3259  	protected static function get_style_nodes( $theme_json, $selectors = array(), $options = array() ) {
3260          $nodes = array();
3261          if ( ! isset( $theme_json['styles'] ) ) {
3262              return $nodes;
3263          }
3264  
3265          // Top-level.
3266          $nodes[] = array(
3267              'path'     => array( 'styles' ),
3268              'selector' => static::ROOT_BLOCK_SELECTOR,
3269          );
3270  
3271          if ( isset( $theme_json['styles']['elements'] ) ) {
3272              foreach ( self::ELEMENTS as $element => $selector ) {
3273                  if ( ! isset( $theme_json['styles']['elements'][ $element ] ) ) {
3274                      continue;
3275                  }
3276                  $nodes[] = array(
3277                      'path'     => array( 'styles', 'elements', $element ),
3278                      'selector' => static::ELEMENTS[ $element ],
3279                  );
3280  
3281                  // Handle any pseudo selectors for the element.
3282                  if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) {
3283                      foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
3284  
3285                          if ( isset( $theme_json['styles']['elements'][ $element ][ $pseudo_selector ] ) ) {
3286                              $nodes[] = array(
3287                                  'path'     => array( 'styles', 'elements', $element ),
3288                                  'selector' => static::append_to_selector( static::ELEMENTS[ $element ], $pseudo_selector ),
3289                              );
3290                          }
3291                      }
3292                  }
3293              }
3294          }
3295  
3296          // Blocks.
3297          if ( ! isset( $theme_json['styles']['blocks'] ) ) {
3298              return $nodes;
3299          }
3300  
3301          $block_nodes = static::get_block_nodes( $theme_json, $selectors, $options );
3302          foreach ( $block_nodes as $block_node ) {
3303              $nodes[] = $block_node;
3304          }
3305  
3306          /**
3307           * Filters the list of style nodes with metadata.
3308           *
3309           * This allows for things like loading block CSS independently.
3310           *
3311           * @since 6.1.0
3312           *
3313           * @param array $nodes Style nodes with metadata.
3314           */
3315          return apply_filters( 'wp_theme_json_get_style_nodes', $nodes );
3316      }
3317  
3318      /**
3319       * A public helper to get the block nodes from a theme.json file.
3320       *
3321       * @since 6.1.0
3322       *
3323       * @return array The block nodes in theme.json.
3324       */
3325  	public function get_styles_block_nodes() {
3326          return static::get_block_nodes( $this->theme_json );
3327      }
3328  
3329      /**
3330       * Returns a filtered declarations array if there is a separator block with only a background
3331       * style defined in theme.json by adding a color attribute to reflect the changes in the front.
3332       *
3333       * @since 6.1.1
3334       *
3335       * @param array $declarations List of declarations.
3336       * @return array $declarations List of declarations filtered.
3337       */
3338  	private static function update_separator_declarations( $declarations ) {
3339          $background_color     = '';
3340          $border_color_matches = false;
3341          $text_color_matches   = false;
3342  
3343          foreach ( $declarations as $declaration ) {
3344              if ( 'background-color' === $declaration['name'] && ! $background_color && isset( $declaration['value'] ) ) {
3345                  $background_color = $declaration['value'];
3346              } elseif ( 'border-color' === $declaration['name'] ) {
3347                  $border_color_matches = true;
3348              } elseif ( 'color' === $declaration['name'] ) {
3349                  $text_color_matches = true;
3350              }
3351  
3352              if ( $background_color && $border_color_matches && $text_color_matches ) {
3353                  break;
3354              }
3355          }
3356  
3357          if ( $background_color && ! $border_color_matches && ! $text_color_matches ) {
3358              $declarations[] = array(
3359                  'name'  => 'color',
3360                  'value' => $background_color,
3361              );
3362          }
3363  
3364          return $declarations;
3365      }
3366  
3367      /**
3368       * Updates the text indent selector for paragraph blocks based on the textIndent setting.
3369       *
3370       * The textIndent setting can be 'subsequent' (default), 'all', or false.
3371       * When set to 'all', the selector should be '.wp-block-paragraph' instead of
3372       * '.wp-block-paragraph + .wp-block-paragraph' to apply indent to all paragraphs.
3373       *
3374       * @since 7.0.0
3375       *
3376       * @param array  $feature_declarations The feature declarations keyed by selector.
3377       * @param array  $settings             The theme.json settings.
3378       * @param string $block_name           The block name being processed.
3379       * @return array The updated feature declarations.
3380       */
3381  	private static function update_paragraph_text_indent_selector( $feature_declarations, $settings, $block_name ) {
3382          if ( 'core/paragraph' !== $block_name ) {
3383              return $feature_declarations;
3384          }
3385  
3386          // Check block-level settings first, then fall back to global settings.
3387          $block_settings      = $settings['blocks']['core/paragraph'] ?? null;
3388          $text_indent_setting = $block_settings['typography']['textIndent']
3389              ?? $settings['typography']['textIndent']
3390              ?? 'subsequent';
3391  
3392          if ( 'all' !== $text_indent_setting ) {
3393              return $feature_declarations;
3394          }
3395  
3396          // Look for the text indent selector and replace it.
3397          $old_selector = '.wp-block-paragraph + .wp-block-paragraph';
3398          $new_selector = '.wp-block-paragraph';
3399  
3400          if ( isset( $feature_declarations[ $old_selector ] ) ) {
3401              $declarations = $feature_declarations[ $old_selector ];
3402              unset( $feature_declarations[ $old_selector ] );
3403              $feature_declarations[ $new_selector ] = $declarations;
3404          }
3405  
3406          return $feature_declarations;
3407      }
3408  
3409      /**
3410       * Updates button width declarations to use a calc() formula for percentage values.
3411       *
3412       * When a percentage width is set on the Button block via Global Styles, the
3413       * resulting CSS needs to account for block gap spacing so that buttons tile
3414       * correctly on a row (e.g. 4 buttons at 25% width all fit on one row).
3415       *
3416       * This mirrors the dynamic calc() formula applied at the block instance level
3417       * in the button block's stylesheet (style.scss).
3418       *
3419       * @since 7.1.0
3420       *
3421       * @param array $feature_declarations The feature declarations keyed by selector.
3422       * @param array $settings             The theme.json settings.
3423       * @return array The updated feature declarations.
3424       */
3425  	private static function update_button_width_declarations( $feature_declarations, $settings ) {
3426          if ( ! isset( $feature_declarations['.wp-block-button'] ) ) {
3427              return $feature_declarations;
3428          }
3429  
3430          foreach ( $feature_declarations['.wp-block-button'] as &$declaration ) {
3431              if ( 'width' !== $declaration['name'] || ! isset( $declaration['value'] ) ) {
3432                  continue;
3433              }
3434  
3435              $value      = $declaration['value'];
3436              $percentage = null;
3437  
3438              // Case 1: Direct percentage value e.g. "25%".
3439              if ( is_string( $value ) && str_ends_with( $value, '%' ) ) {
3440                  $percentage = (float) $value;
3441              }
3442  
3443              // Case 2: Preset CSS var e.g. "var(--wp--preset--dimension--50)".
3444              if ( null === $percentage && is_string( $value ) && str_starts_with( $value, 'var(--wp--preset--dimension--' ) ) {
3445                  // Extract the slug from the var name.
3446                  $slug = substr( $value, strlen( 'var(--wp--preset--dimension--' ), -1 );
3447  
3448                  /*
3449                   * Look up the preset size across all origins.
3450                   * Check block-level settings first (core/button), then top-level settings.
3451                   */
3452                  $dimension_sizes = ( $settings['blocks']['core/button']['dimensions']['dimensionSizes'] ?? array() )
3453                      + ( $settings['dimensions']['dimensionSizes'] ?? array() );
3454                  foreach ( $dimension_sizes as $origin_sizes ) {
3455                      if ( ! is_array( $origin_sizes ) ) {
3456                          continue;
3457                      }
3458                      foreach ( $origin_sizes as $preset ) {
3459                          if ( isset( $preset['slug'] ) && $slug === $preset['slug'] && isset( $preset['size'] ) ) {
3460                              $size = $preset['size'];
3461                              if ( is_string( $size ) && str_ends_with( $size, '%' ) ) {
3462                                  $percentage = (float) $size;
3463                              }
3464                              break 2;
3465                          }
3466                      }
3467                  }
3468              }
3469  
3470              if ( null === $percentage ) {
3471                  continue;
3472              }
3473  
3474              /*
3475               * Apply the same calc() formula as the block instance level (style.scss).
3476               * The numeric percentage value is used as a unitless number:
3477               * - Multiplied by 1% to get the percentage width.
3478               * - Divided by 100 to calculate the gap adjustment proportion.
3479               */
3480              $declaration['value'] = sprintf(
3481                  'calc(%s * 1%% - (var(--wp--style--block-gap, 0.5em) * (1 - %s / 100)))',
3482                  $percentage,
3483                  $percentage
3484              );
3485          }
3486          unset( $declaration );
3487  
3488          return $feature_declarations;
3489      }
3490  
3491      /**
3492       * An internal method to get the block nodes from a theme.json file.
3493       *
3494       * @since 6.1.0
3495       * @since 6.3.0 Refactored and stabilized selectors API.
3496       * @since 6.6.0 Added optional selectors and options for generating block nodes.
3497       * @since 6.7.0 Added $include_node_paths_only option.
3498       * @since 7.1.0 Added responsive block nodes for breakpoint-based styles.
3499       *
3500       * @param array $theme_json The theme.json converted to an array.
3501       * @param array $selectors  Optional list of selectors per block.
3502       * @param array $options {
3503       *     Optional. An array of options for now used for internal purposes only (may change without notice).
3504       *
3505       *     @type bool $include_block_style_variations Include nodes for block style variations. Default false.
3506       *     @type bool $include_node_paths_only        Return only block nodes node paths. Default false.
3507       * }
3508       * @return array The block nodes in theme.json.
3509       */
3510  	private static function get_block_nodes( $theme_json, $selectors = array(), $options = array() ) {
3511          $nodes = array();
3512  
3513          if ( ! isset( $theme_json['styles']['blocks'] ) ) {
3514              return $nodes;
3515          }
3516  
3517          $include_variations       = $options['include_block_style_variations'] ?? false;
3518          $include_node_paths_only  = $options['include_node_paths_only'] ?? false;
3519          $responsive_media_queries = static::get_viewport_media_queries( $theme_json['settings']['viewport'] ?? null );
3520  
3521          // If only node paths are to be returned, skip selector assignment.
3522          if ( ! $include_node_paths_only ) {
3523              $selectors = empty( $selectors ) ? static::get_blocks_metadata() : $selectors;
3524          }
3525  
3526          foreach ( $theme_json['styles']['blocks'] as $name => $node ) {
3527              $node_path = array( 'styles', 'blocks', $name );
3528              if ( $include_node_paths_only ) {
3529                  $variation_paths = array();
3530                  if ( $include_variations && isset( $node['variations'] ) ) {
3531                      foreach ( $node['variations'] as $variation => $variation_node ) {
3532                          $variation_paths[] = array(
3533                              'path' => array( 'styles', 'blocks', $name, 'variations', $variation ),
3534                          );
3535                      }
3536                  }
3537                  $node = array(
3538                      'path' => $node_path,
3539                  );
3540                  if ( ! empty( $variation_paths ) ) {
3541                      $node['variations'] = $variation_paths;
3542                  }
3543                  $nodes[] = $node;
3544              } else {
3545                  $selector = null;
3546                  if ( isset( $selectors[ $name ]['selector'] ) ) {
3547                      $selector = $selectors[ $name ]['selector'];
3548                  }
3549  
3550                  $duotone_selector = null;
3551                  if ( isset( $selectors[ $name ]['duotone'] ) ) {
3552                      $duotone_selector = $selectors[ $name ]['duotone'];
3553                  }
3554  
3555                  $feature_selectors = null;
3556                  if ( isset( $selectors[ $name ]['selectors'] ) ) {
3557                      $feature_selectors = $selectors[ $name ]['selectors'];
3558                  }
3559  
3560                  $variation_selectors = array();
3561  
3562                  if ( $include_variations && isset( $node['variations'] ) ) {
3563                      foreach ( $node['variations'] as $variation => $node ) {
3564                          $variation_selectors[] = array(
3565                              'name'     => $variation,
3566                              'path'     => array( 'styles', 'blocks', $name, 'variations', $variation ),
3567                              'selector' => $selectors[ $name ]['styleVariations'][ $variation ],
3568                          );
3569                      }
3570                  }
3571  
3572                  $nodes[] = array(
3573                      'name'       => $name,
3574                      'path'       => $node_path,
3575                      'selector'   => $selector,
3576                      'selectors'  => $feature_selectors,
3577                      'elements'   => $selectors[ $name ]['elements'] ?? array(),
3578                      'duotone'    => $duotone_selector,
3579                      'variations' => $variation_selectors,
3580                      'css'        => $selector,
3581                  );
3582  
3583                  // Responsive block nodes: emit one node per breakpoint that has styles.
3584                  // These are rendered immediately after the base block node so that
3585                  // the cascade order is: .block{} → @media{.block{}}
3586                  foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3587                      if ( isset( $theme_json['styles']['blocks'][ $name ][ $breakpoint ] ) ) {
3588                          $nodes[] = array(
3589                              'name'        => $name,
3590                              'path'        => array( 'styles', 'blocks', $name, $breakpoint ),
3591                              'media_query' => $responsive_media_queries[ $breakpoint ],
3592                              'selector'    => $selector,
3593                              'selectors'   => $feature_selectors,
3594                              'elements'    => $selectors[ $name ]['elements'] ?? array(),
3595                              'variations'  => $variation_selectors,
3596                              'css'         => $selector,
3597                          );
3598                      }
3599                  }
3600  
3601                  // Handle any pseudo selectors for the block.
3602                  if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $name ] ) ) {
3603                      foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $name ] as $pseudo_selector ) {
3604                          $has_pseudo            = isset( $theme_json['styles']['blocks'][ $name ][ $pseudo_selector ] );
3605                          $has_responsive_pseudo = false;
3606                          foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3607                              if ( isset( $theme_json['styles']['blocks'][ $name ][ $breakpoint ][ $pseudo_selector ] ) ) {
3608                                  $has_responsive_pseudo = true;
3609                                  break;
3610                              }
3611                          }
3612  
3613                          if ( ! $has_pseudo && ! $has_responsive_pseudo ) {
3614                              continue;
3615                          }
3616  
3617                          /*
3618                           * Append the pseudo-selector to each feature selector so that
3619                           * get_feature_declarations_for_node generates CSS scoped to the
3620                           * pseudo-state (e.g. '.wp-block-button:hover') rather than the
3621                           * default state (e.g. '.wp-block-button').
3622                           */
3623                          $pseudo_feature_selectors = array();
3624                          foreach ( $feature_selectors ?? array() as $feature => $feature_selector ) {
3625                              if ( is_array( $feature_selector ) ) {
3626                                  $pseudo_feature_selectors[ $feature ] = array();
3627                                  foreach ( $feature_selector as $subfeature => $subfeature_selector ) {
3628                                      $pseudo_feature_selectors[ $feature ][ $subfeature ] = static::append_to_selector( $subfeature_selector, $pseudo_selector );
3629                                  }
3630                              } else {
3631                                  $pseudo_feature_selectors[ $feature ] = static::append_to_selector( $feature_selector, $pseudo_selector );
3632                              }
3633                          }
3634  
3635                          if ( $has_pseudo ) {
3636                              $nodes[] = array(
3637                                  'name'       => $name,
3638                                  'path'       => array( 'styles', 'blocks', $name, $pseudo_selector ),
3639                                  'selector'   => static::append_to_selector( $selector, $pseudo_selector ),
3640                                  'selectors'  => $pseudo_feature_selectors,
3641                                  'elements'   => $selectors[ $name ]['elements'] ?? array(),
3642                                  'duotone'    => $duotone_selector,
3643                                  'variations' => $variation_selectors,
3644                                  'css'        => static::append_to_selector( $selector, $pseudo_selector ),
3645                              );
3646                          }
3647  
3648                          // Responsive pseudo nodes: emit one node per breakpoint that has
3649                          // this pseudo state, immediately after the default pseudo node.
3650                          // Cascade order: .block:hover{} → @media{.block:hover{}}
3651                          foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3652                              if ( isset( $theme_json['styles']['blocks'][ $name ][ $breakpoint ][ $pseudo_selector ] ) ) {
3653                                  $nodes[] = array(
3654                                      'name'        => $name,
3655                                      'path'        => array( 'styles', 'blocks', $name, $breakpoint, $pseudo_selector ),
3656                                      'media_query' => $responsive_media_queries[ $breakpoint ],
3657                                      'selector'    => static::append_to_selector( $selector, $pseudo_selector ),
3658                                      'selectors'   => $pseudo_feature_selectors,
3659                                      'elements'    => $selectors[ $name ]['elements'] ?? array(),
3660                                      'variations'  => $variation_selectors,
3661                                      'css'         => static::append_to_selector( $selector, $pseudo_selector ),
3662                                  );
3663                              }
3664                          }
3665                      }
3666                  }
3667  
3668                  // Handle custom states (e.g. '-current' for navigation).
3669                  if ( isset( static::VALID_BLOCK_CUSTOM_STATES[ $name ] ) ) {
3670                      foreach ( static::VALID_BLOCK_CUSTOM_STATES[ $name ] as $custom_state ) {
3671                          if (
3672                              isset( $theme_json['styles']['blocks'][ $name ][ $custom_state ] ) &&
3673                              isset( $selectors[ $name ]['states'][ $custom_state ] )
3674                          ) {
3675                              $custom_css_selector = $selectors[ $name ]['states'][ $custom_state ];
3676                              $nodes[]             = array(
3677                                  'name'       => $name,
3678                                  'path'       => array( 'styles', 'blocks', $name, $custom_state ),
3679                                  'selector'   => $custom_css_selector,
3680                                  'selectors'  => $feature_selectors,
3681                                  'elements'   => $selectors[ $name ]['elements'] ?? array(),
3682                                  'duotone'    => $duotone_selector,
3683                                  'variations' => $variation_selectors,
3684                                  'css'        => $custom_css_selector,
3685                              );
3686  
3687                              // Sub-pseudo-selectors within the custom state.
3688                              if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $name ] ) ) {
3689                                  foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $name ] as $pseudo ) {
3690                                      if ( isset( $theme_json['styles']['blocks'][ $name ][ $custom_state ][ $pseudo ] ) ) {
3691                                          $compound_css_selector = static::append_to_selector( $custom_css_selector, $pseudo );
3692                                          $nodes[]               = array(
3693                                              'name'       => $name,
3694                                              'path'       => array( 'styles', 'blocks', $name, $custom_state, $pseudo ),
3695                                              'selector'   => $compound_css_selector,
3696                                              'selectors'  => $feature_selectors,
3697                                              'elements'   => $selectors[ $name ]['elements'] ?? array(),
3698                                              'duotone'    => $duotone_selector,
3699                                              'variations' => $variation_selectors,
3700                                              'css'        => $compound_css_selector,
3701                                          );
3702                                      }
3703                                  }
3704                              }
3705                          }
3706                      }
3707                  }
3708              }
3709              if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'] ) ) {
3710                  foreach ( $theme_json['styles']['blocks'][ $name ]['elements'] as $element => $node ) {
3711                      $element_path = array( 'styles', 'blocks', $name, 'elements', $element );
3712                      if ( $include_node_paths_only ) {
3713                          $nodes[] = array(
3714                              'path' => $element_path,
3715                          );
3716                          continue;
3717                      }
3718  
3719                      $element_selector = $selectors[ $name ]['elements'][ $element ];
3720  
3721                      $nodes[] = array(
3722                          'path'     => $element_path,
3723                          'selector' => $element_selector,
3724                      );
3725  
3726                      // Responsive element nodes: one node per breakpoint that has
3727                      // styles for this element. Cascade: a{} → @media{a{}}
3728                      foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3729                          if ( isset( $theme_json['styles']['blocks'][ $name ][ $breakpoint ]['elements'][ $element ] ) ) {
3730                              $nodes[] = array(
3731                                  'path'        => array( 'styles', 'blocks', $name, $breakpoint, 'elements', $element ),
3732                                  'selector'    => $element_selector,
3733                                  'media_query' => $responsive_media_queries[ $breakpoint ],
3734                              );
3735                          }
3736                      }
3737  
3738                      // Handle any pseudo selectors for the element.
3739                      if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) {
3740                          foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
3741                              // Create element pseudo node if default or any responsive breakpoint has the pseudo.
3742                              $has_element_pseudo = isset( $theme_json['styles']['blocks'][ $name ]['elements'][ $element ][ $pseudo_selector ] );
3743                              if ( ! $has_element_pseudo ) {
3744                                  foreach ( array_keys( $responsive_media_queries ) as $bp ) {
3745                                      if ( isset( $theme_json['styles']['blocks'][ $name ][ $bp ]['elements'][ $element ][ $pseudo_selector ] ) ) {
3746                                          $has_element_pseudo = true;
3747                                          break;
3748                                      }
3749                                  }
3750                              }
3751  
3752                              if ( $has_element_pseudo ) {
3753                                  $element_pseudo_path = array( 'styles', 'blocks', $name, 'elements', $element );
3754                                  if ( $include_node_paths_only ) {
3755                                      $nodes[] = array(
3756                                          'path' => $element_pseudo_path,
3757                                      );
3758                                      continue;
3759                                  }
3760  
3761                                  $nodes[] = array(
3762                                      'path'     => $element_pseudo_path,
3763                                      'selector' => static::append_to_selector( $element_selector, $pseudo_selector ),
3764                                  );
3765  
3766                                  // Responsive element pseudo nodes: one node per breakpoint
3767                                  // that has this pseudo state for this element.
3768                                  // Cascade: a:hover{} → @media{a:hover{}}
3769                                  foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3770                                      if ( isset( $theme_json['styles']['blocks'][ $name ][ $breakpoint ]['elements'][ $element ][ $pseudo_selector ] ) ) {
3771                                          $nodes[] = array(
3772                                              'path'        => array( 'styles', 'blocks', $name, $breakpoint, 'elements', $element ),
3773                                              'selector'    => static::append_to_selector( $element_selector, $pseudo_selector ),
3774                                              'media_query' => $responsive_media_queries[ $breakpoint ],
3775                                          );
3776                                      }
3777                                  }
3778                              }
3779                          }
3780                      }
3781                  }
3782              }
3783          }
3784  
3785          return $nodes;
3786      }
3787  
3788      /**
3789       * Gets the CSS rules for a particular block from theme.json.
3790       *
3791       * @since 6.1.0
3792       * @since 6.6.0 Setting a min-height of HTML when root styles have a background gradient or image.
3793       *              Updated general global styles specificity to 0-1-0.
3794       *              Fixed custom CSS output in block style variations.
3795       *
3796       * @param array $block_metadata Metadata about the block to get styles for.
3797       * @return string Styles for the block.
3798       */
3799  	public function get_styles_for_block( $block_metadata ) {
3800          $node                     = _wp_array_get( $this->theme_json, $block_metadata['path'], array() );
3801          $use_root_padding         = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments'];
3802          $selector                 = $block_metadata['selector'];
3803          $settings                 = $this->theme_json['settings'] ?? array();
3804          $feature_declarations     = static::get_feature_declarations_for_node( $block_metadata, $node );
3805          $is_root_selector         = static::ROOT_BLOCK_SELECTOR === $selector;
3806          $media_query              = $block_metadata['media_query'] ?? null;
3807          $responsive_media_queries = static::get_viewport_media_queries( $settings['viewport'] ?? null );
3808  
3809          // Update text indent selector for paragraph blocks based on the textIndent setting.
3810          $block_name           = $block_metadata['name'] ?? null;
3811          $feature_declarations = static::update_paragraph_text_indent_selector( $feature_declarations, $settings, $block_name );
3812          $block_elements       = $block_metadata['elements'] ?? array();
3813  
3814          // Update button width declarations for percentage values to use calc() with block gap.
3815          $feature_declarations = static::update_button_width_declarations( $feature_declarations, $settings );
3816  
3817          // If there are style variations, generate the declarations for them, including any feature selectors the block may have.
3818          $style_variation_declarations          = array();
3819          $style_variation_custom_css            = array();
3820          $style_variation_responsive_css        = array();
3821          $style_variation_responsive_pseudo_css = array();
3822          $style_variation_layout_metadata       = array();
3823          if ( ! $media_query && ! empty( $block_metadata['variations'] ) ) {
3824              foreach ( $block_metadata['variations'] as $style_variation ) {
3825                  $style_variation_node = _wp_array_get( $this->theme_json, $style_variation['path'], array() );
3826  
3827                  // Generate any feature/subfeature style declarations for the current style variation.
3828                  $variation_declarations = static::get_feature_declarations_for_node( $block_metadata, $style_variation_node );
3829  
3830                  // Update text indent selector for paragraph blocks based on the textIndent setting.
3831                  $variation_declarations = static::update_paragraph_text_indent_selector( $variation_declarations, $settings, $block_name );
3832  
3833                  // Update button width declarations for percentage values to use calc() with block gap.
3834                  $variation_declarations = static::update_button_width_declarations( $variation_declarations, $settings );
3835  
3836                  // Combine selectors with style variation's selector and add to overall style variation declarations.
3837                  foreach ( $variation_declarations as $current_selector => $new_declarations ) {
3838                      $combined_selectors = static::get_block_style_variation_feature_selector( $style_variation, $current_selector );
3839  
3840                      // Add the new declarations to the overall results under the modified selector.
3841                      $style_variation_declarations[ $combined_selectors ] = $new_declarations;
3842                  }
3843  
3844                  // Compute declarations for remaining styles not covered by feature level selectors.
3845                  $style_variation_declarations[ $style_variation['selector'] ] = static::compute_style_properties( $style_variation_node, $settings, null, $this->theme_json );
3846  
3847                  // Process pseudo-selectors for this variation (e.g., :hover, :focus)
3848                  if ( isset( $block_metadata['name'] ) ) {
3849                      $block_name = $block_metadata['name'];
3850                  } elseif ( in_array( 'blocks', $block_metadata['path'], true ) && count( $block_metadata['path'] ) >= 3 ) {
3851                      $block_name = static::get_block_name_from_metadata_path( $block_metadata );
3852                  } else {
3853                      $block_name = null;
3854                  }
3855                  $variation_pseudo_declarations = $this->process_pseudo_selectors( $style_variation_node, $style_variation['selector'], $settings, $block_name, $block_metadata, $style_variation );
3856                  $style_variation_declarations  = array_merge( $style_variation_declarations, $variation_pseudo_declarations );
3857  
3858                  // Store custom CSS for the style variation.
3859                  if ( isset( $style_variation_node['css'] ) ) {
3860                      $style_variation_custom_css[ $style_variation['selector'] ] = $this->process_blocks_custom_css( $style_variation_node['css'], $style_variation['selector'] );
3861                  }
3862  
3863                  // Store variation metadata and node for layout styles generation.
3864                  // Only store if the variation has blockGap defined.
3865                  if ( isset( $style_variation_node['spacing']['blockGap'] ) ) {
3866                      // Append block selector to the variation selector for proper targeting.
3867                      $variation_metadata_with_selector                                = $style_variation;
3868                      $variation_metadata_with_selector['selector']                    = $style_variation['selector'] . $block_metadata['css'];
3869                      $style_variation_layout_metadata[ $style_variation['selector'] ] = array(
3870                          'metadata' => $variation_metadata_with_selector,
3871                          'node'     => $style_variation_node,
3872                      );
3873                  }
3874  
3875                  // Store responsive breakpoint CSS for the style variation.
3876                  // This includes both base properties and feature-level selectors.
3877                  $variation_responsive_css        = '';
3878                  $variation_responsive_pseudo_css = '';
3879  
3880                  foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
3881                      if ( ! isset( $style_variation_node[ $breakpoint ] ) ) {
3882                          continue;
3883                      }
3884  
3885                      $breakpoint_node  = $style_variation_node[ $breakpoint ];
3886                      $breakpoint_media = $responsive_media_queries[ $breakpoint ];
3887                      // Process feature-level declarations for this breakpoint.
3888                      $breakpoint_feature_declarations = static::get_feature_declarations_for_node( $block_metadata, $breakpoint_node );
3889                      $breakpoint_feature_declarations = static::update_paragraph_text_indent_selector( $breakpoint_feature_declarations, $settings, $block_name );
3890                      $breakpoint_feature_declarations = static::update_button_width_declarations( $breakpoint_feature_declarations, $settings );
3891                      foreach ( $breakpoint_feature_declarations as $feature_selector => $feature_decl ) {
3892                          $combined_selectors = static::get_block_style_variation_feature_selector( $style_variation, $feature_selector );
3893  
3894                          $feature_ruleset           = static::to_ruleset( ':root :where(' . $combined_selectors . ')', $feature_decl );
3895                          $variation_responsive_css .= $breakpoint_media . '{' . $feature_ruleset . '}';
3896                      }
3897  
3898                      // Process base properties for this breakpoint.
3899                      $breakpoint_declarations = static::compute_style_properties( $breakpoint_node, $settings, null, $this->theme_json );
3900                      if ( ! empty( $breakpoint_declarations ) ) {
3901                          $base_ruleset              = static::to_ruleset( ':root :where(' . $style_variation['selector'] . ')', $breakpoint_declarations );
3902                          $variation_responsive_css .= $breakpoint_media . '{' . $base_ruleset . '}';
3903                      }
3904  
3905                      $breakpoint_pseudo_declarations = $this->process_pseudo_selectors( $breakpoint_node, $style_variation['selector'], $settings, $block_name, $block_metadata, $style_variation );
3906                      foreach ( $breakpoint_pseudo_declarations as $pseudo_selector => $pseudo_declarations ) {
3907                          if ( empty( $pseudo_declarations ) ) {
3908                              continue;
3909                          }
3910                          $pseudo_ruleset                   = static::to_ruleset( ':root :where(' . $pseudo_selector . ')', $pseudo_declarations );
3911                          $variation_responsive_pseudo_css .= $breakpoint_media . '{' . $pseudo_ruleset . '}';
3912                      }
3913  
3914                      // Process custom CSS for this breakpoint.
3915                      if ( isset( $breakpoint_node['css'] ) ) {
3916                          $breakpoint_custom_css     = static::process_blocks_custom_css( $breakpoint_node['css'], $style_variation['selector'] );
3917                          $variation_responsive_css .= $breakpoint_media . '{' . $breakpoint_custom_css . '}';
3918                      }
3919  
3920                      // Process blockGap responsive layout styles for this variation.
3921                      if ( isset( $breakpoint_node['spacing']['blockGap'] ) ) {
3922                          $variation_layout_metadata             = $style_variation;
3923                          $variation_layout_metadata['selector'] = $style_variation['selector'] . $block_metadata['css'];
3924                          $variation_responsive_css             .= $this->get_layout_styles(
3925                              $variation_layout_metadata,
3926                              array(
3927                                  'node'        => $breakpoint_node,
3928                                  'media_query' => $breakpoint_media,
3929                              )
3930                          );
3931                      }
3932  
3933                      // Process nested element styles for this breakpoint state.
3934                      if ( isset( $breakpoint_node['elements'] ) && ! empty( $block_elements ) ) {
3935                          foreach ( $breakpoint_node['elements'] as $element_name => $element_node ) {
3936                              if ( ! isset( $block_elements[ $element_name ] ) ) {
3937                                  continue;
3938                              }
3939  
3940                              $variation_element_selector = static::get_block_style_variation_feature_selector( $style_variation, $block_elements[ $element_name ] );
3941  
3942                              $element_declarations = static::compute_style_properties( $element_node, $settings, null, $this->theme_json );
3943                              if ( ! empty( $element_declarations ) ) {
3944                                  $element_ruleset           = static::to_ruleset( ':root :where(' . $variation_element_selector . ')', $element_declarations );
3945                                  $variation_responsive_css .= $breakpoint_media . '{' . $element_ruleset . '}';
3946                              }
3947  
3948                              if ( isset( $element_node['css'] ) ) {
3949                                  $element_custom_css        = static::process_blocks_custom_css( $element_node['css'], $variation_element_selector );
3950                                  $variation_responsive_css .= $breakpoint_media . '{' . $element_custom_css . '}';
3951                              }
3952  
3953                              if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] ) ) {
3954                                  foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] as $pseudo_selector ) {
3955                                      if ( ! isset( $element_node[ $pseudo_selector ] ) ) {
3956                                          continue;
3957                                      }
3958  
3959                                      $pseudo_declarations = static::compute_style_properties( $element_node[ $pseudo_selector ], $settings, null, $this->theme_json );
3960                                      if ( empty( $pseudo_declarations ) ) {
3961                                          continue;
3962                                      }
3963  
3964                                      $pseudo_selector_ruleset          = static::to_ruleset( ':root :where(' . static::append_to_selector( $variation_element_selector, $pseudo_selector ) . ')', $pseudo_declarations );
3965                                      $variation_responsive_pseudo_css .= $breakpoint_media . '{' . $pseudo_selector_ruleset . '}';
3966                                  }
3967                              }
3968                          }
3969                      }
3970                  }
3971  
3972                  if ( ! empty( $variation_responsive_css ) ) {
3973                      $style_variation_responsive_css[ $style_variation['selector'] ] = $variation_responsive_css;
3974                  }
3975                  if ( ! empty( $variation_responsive_pseudo_css ) ) {
3976                      $style_variation_responsive_pseudo_css[ $style_variation['selector'] ] = $variation_responsive_pseudo_css;
3977                  }
3978              }
3979          }
3980          /*
3981           * Get a reference to element name from path.
3982           * $block_metadata['path'] = array( 'styles','elements','link' );
3983           * Make sure that $block_metadata['path'] describes an element node, like [ 'styles', 'element', 'link' ].
3984           * Skip non-element paths like just ['styles'].
3985           */
3986          $is_processing_element = in_array( 'elements', $block_metadata['path'], true );
3987  
3988          $current_element = $is_processing_element ? $block_metadata['path'][ count( $block_metadata['path'] ) - 1 ] : null;
3989  
3990          $element_pseudo_allowed = array();
3991  
3992          if ( isset( $current_element, static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) ) {
3993              $element_pseudo_allowed = static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ];
3994          }
3995  
3996          /*
3997           * Check for allowed pseudo classes (e.g. ":hover") from the $selector ("a:hover").
3998           * This also resets the array keys.
3999           */
4000          $pseudo_matches = array_values(
4001              array_filter(
4002                  $element_pseudo_allowed,
4003                  static function ( $pseudo_selector ) use ( $selector ) {
4004                      /*
4005                       * Check if the pseudo selector is in the current selector,
4006                       * ensuring it is not followed by a dash (e.g., :focus should not match :focus-visible).
4007                       */
4008                      return preg_match( '/' . preg_quote( $pseudo_selector, '/' ) . '(?!-)/', $selector ) === 1;
4009                  }
4010              )
4011          );
4012  
4013          $pseudo_selector = $pseudo_matches[0] ?? null;
4014  
4015          /*
4016           * If the current selector is a pseudo selector that's defined in the allow list for the current
4017           * element then compute the style properties for it.
4018           * Otherwise just compute the styles for the default selector as normal.
4019           */
4020          if ( $pseudo_selector && isset( $node[ $pseudo_selector ] ) &&
4021              isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] )
4022              && in_array( $pseudo_selector, static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ], true )
4023          ) {
4024              $declarations = static::compute_style_properties( $node[ $pseudo_selector ], $settings, null, $this->theme_json, $selector, $use_root_padding );
4025          } else {
4026              /*
4027               * For block pseudo-selector nodes (e.g. ':hover'), $node has already had any
4028               * feature-selector properties (e.g. writingMode) removed by get_feature_declarations_for_node,
4029               * so those properties are not output twice.
4030               */
4031              $declarations = static::compute_style_properties( $node, $settings, null, $this->theme_json, $selector, $use_root_padding );
4032          }
4033  
4034          $block_rules = '';
4035  
4036          /*
4037           * 1. Bespoke declaration modifiers:
4038           * - 'filter': Separate the declarations that use the general selector
4039           * from the ones using the duotone selector.
4040           * - 'background|background-image': set the html min-height to 100%
4041           * to ensure the background covers the entire viewport.
4042           */
4043          $declarations_duotone       = array();
4044          $should_set_root_min_height = false;
4045  
4046          foreach ( $declarations as $index => $declaration ) {
4047              if ( 'filter' === $declaration['name'] ) {
4048                  /*
4049                   * 'unset' filters happen when a filter is unset
4050                   * in the site-editor UI. Because the 'unset' value
4051                   * in the user origin overrides the value in the
4052                   * theme origin, we can skip rendering anything
4053                   * here as no filter needs to be applied anymore.
4054                   * So only add declarations to with values other
4055                   * than 'unset'.
4056                   */
4057                  if ( 'unset' !== $declaration['value'] ) {
4058                      $declarations_duotone[] = $declaration;
4059                  }
4060                  unset( $declarations[ $index ] );
4061              }
4062  
4063              if ( $is_root_selector && ( 'background-image' === $declaration['name'] || 'background' === $declaration['name'] ) ) {
4064                  $should_set_root_min_height = true;
4065              }
4066          }
4067  
4068          /*
4069           * If root styles has a background-image or a background (gradient) set,
4070           * set the min-height to '100%'. Minus `--wp-admin--admin-bar--height` for logged-in view.
4071           * Setting the CSS rule on the HTML tag ensures background gradients and images behave similarly,
4072           * and matches the behavior of the site editor.
4073           */
4074          if ( $should_set_root_min_height ) {
4075              $block_rules .= static::to_ruleset(
4076                  'html',
4077                  array(
4078                      array(
4079                          'name'  => 'min-height',
4080                          'value' => 'calc(100% - var(--wp-admin--admin-bar--height, 0px))',
4081                      ),
4082                  )
4083              );
4084          }
4085  
4086          // Update declarations if there are separators with only background color defined.
4087          if ( '.wp-block-separator' === $selector ) {
4088              $declarations = static::update_separator_declarations( $declarations );
4089          }
4090  
4091          /*
4092           * Root selector (body) styles should not be wrapped in `:root where()` to keep
4093           * specificity at (0,0,1) and maintain backwards compatibility.
4094           *
4095           * Top-level element styles using element-only specificity selectors should
4096           * not get wrapped in `:root :where()` to maintain backwards compatibility.
4097           *
4098           * Pseudo classes, e.g. :hover, :focus etc., are a class-level selector so
4099           * still need to be wrapped in `:root :where` to cap specificity for nested
4100           * variations etc. Pseudo selectors won't match the ELEMENTS selector exactly.
4101           */
4102          $element_only_selector = $is_root_selector || (
4103              $current_element &&
4104              isset( static::ELEMENTS[ $current_element ] ) &&
4105              // buttons, captions etc. still need `:root :where()` as they are class based selectors.
4106              ! isset( static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $current_element ] ) &&
4107              static::ELEMENTS[ $current_element ] === $selector
4108          );
4109  
4110          // 2. Generate and append the rules that use the general selector.
4111          $general_selector = $element_only_selector ? $selector : ":root :where($selector)";
4112          $block_rules     .= static::to_ruleset( $general_selector, $declarations );
4113  
4114          // 3. Generate and append the rules that use the duotone selector.
4115          if ( isset( $block_metadata['duotone'] ) && ! empty( $declarations_duotone ) ) {
4116              $block_rules .= static::to_ruleset( $block_metadata['duotone'], $declarations_duotone );
4117          }
4118  
4119          // 4. Generate Layout block gap styles.
4120          if (
4121              ! $is_root_selector &&
4122              ! empty( $block_metadata['name'] )
4123          ) {
4124              $block_rules .= $this->get_layout_styles( $block_metadata );
4125          }
4126  
4127          // 5. Generate and append the feature level rulesets.
4128          foreach ( $feature_declarations as $feature_selector => $individual_feature_declarations ) {
4129              $block_rules .= static::to_ruleset( ":root :where($feature_selector)", $individual_feature_declarations );
4130          }
4131  
4132          // 6. Generate and append the style variation rulesets.
4133          foreach ( $style_variation_declarations as $style_variation_selector => $individual_style_variation_declarations ) {
4134              $block_rules .= static::to_ruleset( ":root :where($style_variation_selector)", $individual_style_variation_declarations );
4135              if ( isset( $style_variation_layout_metadata[ $style_variation_selector ] ) ) {
4136                  $variation_data = $style_variation_layout_metadata[ $style_variation_selector ];
4137                  $block_rules   .= $this->get_layout_styles( $variation_data['metadata'], array( 'node' => $variation_data['node'] ) );
4138              }
4139              if ( isset( $style_variation_custom_css[ $style_variation_selector ] ) ) {
4140                  $block_rules .= $style_variation_custom_css[ $style_variation_selector ];
4141              }
4142              if ( isset( $style_variation_responsive_css[ $style_variation_selector ] ) ) {
4143                  $block_rules .= $style_variation_responsive_css[ $style_variation_selector ];
4144              }
4145          }
4146          /*
4147           * Responsive pseudo styles must be output after default pseudo styles
4148           * so viewport state styles win in the cascade.
4149           */
4150          foreach ( $style_variation_responsive_pseudo_css as $responsive_pseudo_css ) {
4151              $block_rules .= $responsive_pseudo_css;
4152          }
4153  
4154          // 7. Generate and append any custom CSS rules.
4155          if ( isset( $node['css'] ) && ! $is_root_selector ) {
4156              $css_feature_selector = $block_metadata['selectors']['css'] ?? null;
4157              if ( is_array( $css_feature_selector ) ) {
4158                  $css_feature_selector = $css_feature_selector['root'] ?? null;
4159              }
4160              $css_selector = is_string( $css_feature_selector ) ? $css_feature_selector : $selector;
4161              $block_rules .= $this->process_blocks_custom_css( $node['css'], $css_selector );
4162          }
4163  
4164          // 8. Wrap the entire block output in a media query if this is a responsive node.
4165          // Responsive nodes are created by get_block_nodes() for each breakpoint and carry
4166          // a 'media_query' key.
4167          if ( $media_query && ! empty( $block_rules ) ) {
4168              $block_rules = $media_query . '{' . $block_rules . '}';
4169          }
4170  
4171          return $block_rules;
4172      }
4173  
4174      /**
4175       * Outputs the CSS for layout rules on the root.
4176       *
4177       * @since 6.1.0
4178       * @since 6.6.0 Use `ROOT_CSS_PROPERTIES_SELECTOR` for CSS custom properties and improved consistency of root padding rules.
4179       *              Updated specificity of body margin reset and first/last child selectors.
4180       * @since 7.0.0 Added `$options` parameter to control alignment styles output for classic themes.
4181       *
4182       * @param string $selector The root node selector.
4183       * @param array  $block_metadata The metadata for the root block.
4184       * @param array  $options        Optional. An array of options for now used for internal purposes only.
4185       * @return string The additional root rules CSS.
4186       */
4187  	public function get_root_layout_rules( $selector, $block_metadata, $options = array() ) {
4188          $css              = '';
4189          $settings         = $this->theme_json['settings'] ?? array();
4190          $use_root_padding = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments'];
4191  
4192          /*
4193           * If there are content and wide widths in theme.json, output them
4194           * as custom properties on the body element so all blocks can use them.
4195           */
4196          if ( isset( $settings['layout']['contentSize'] ) || isset( $settings['layout']['wideSize'] ) ) {
4197              $content_size = $settings['layout']['contentSize'] ?? $settings['layout']['wideSize'];
4198              $content_size = static::is_safe_css_declaration( 'max-width', $content_size ) ? $content_size : 'initial';
4199              $wide_size    = $settings['layout']['wideSize'] ?? $settings['layout']['contentSize'];
4200              $wide_size    = static::is_safe_css_declaration( 'max-width', $wide_size ) ? $wide_size : 'initial';
4201              $css         .= static::ROOT_CSS_PROPERTIES_SELECTOR . ' { --wp--style--global--content-size: ' . $content_size . ';';
4202              $css         .= '--wp--style--global--wide-size: ' . $wide_size . '; }';
4203          }
4204  
4205          /*
4206           * Reset default browser margin on the body element.
4207           * This is set on the body selector **before** generating the ruleset
4208           * from the `theme.json`. This is to ensure that if the `theme.json` declares
4209           * `margin` in its `spacing` declaration for the `body` element then these
4210           * user-generated values take precedence in the CSS cascade.
4211           * @link https://github.com/WordPress/gutenberg/issues/36147.
4212           */
4213          $css .= ':where(body) { margin: 0; }';
4214  
4215          if ( $use_root_padding ) {
4216              // Top and bottom padding are applied to the outer block container.
4217              $css .= '.wp-site-blocks { padding-top: var(--wp--style--root--padding-top); padding-bottom: var(--wp--style--root--padding-bottom); }';
4218              // Right and left padding are applied to the first container with `.has-global-padding` class.
4219              $css .= '.has-global-padding { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }';
4220              // Alignfull children of the container with left and right padding have negative margins so they can still be full width.
4221              $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); }';
4222              // 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.
4223              $css .= '.has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull)) { padding-right: 0; padding-left: 0; }';
4224              // Alignfull direct children of the containers that are targeted by the rule above do not need negative margins.
4225              $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; }';
4226          }
4227  
4228          // Skip outputting alignment styles when base_layout_styles is enabled.
4229          // These styles target .wp-site-blocks which is only used by block themes.
4230          if ( empty( $options['base_layout_styles'] ) ) {
4231              $css .= '.wp-site-blocks > .alignleft { float: left; margin-right: 2em; }';
4232              $css .= '.wp-site-blocks > .alignright { float: right; margin-left: 2em; }';
4233              $css .= '.wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }';
4234          }
4235  
4236          // Block gap styles will be output unless explicitly set to `null`.
4237          if ( isset( $this->theme_json['settings']['spacing']['blockGap'] ) ) {
4238              $block_gap_value = static::get_property_value( $this->theme_json, array( 'styles', 'spacing', 'blockGap' ) );
4239              $css            .= ":where(.wp-site-blocks) > * { margin-block-start: $block_gap_value; margin-block-end: 0; }";
4240              $css            .= ':where(.wp-site-blocks) > :first-child { margin-block-start: 0; }';
4241              $css            .= ':where(.wp-site-blocks) > :last-child { margin-block-end: 0; }';
4242  
4243              // For backwards compatibility, ensure the legacy block gap CSS variable is still available.
4244              $css .= static::ROOT_CSS_PROPERTIES_SELECTOR . " { --wp--style--block-gap: $block_gap_value; }";
4245          }
4246          $css .= $this->get_layout_styles( $block_metadata, $options );
4247  
4248          return $css;
4249      }
4250  
4251      /**
4252       * For metadata values that can either be booleans or paths to booleans, gets the value.
4253       *
4254       *     $data = array(
4255       *       'color' => array(
4256       *         'defaultPalette' => true
4257       *       )
4258       *     );
4259       *
4260       *     static::get_metadata_boolean( $data, false );
4261       *     // => false
4262       *
4263       *     static::get_metadata_boolean( $data, array( 'color', 'defaultPalette' ) );
4264       *     // => true
4265       *
4266       * @since 6.0.0
4267       *
4268       * @param array      $data          The data to inspect.
4269       * @param bool|array $path          Boolean or path to a boolean.
4270       * @param bool       $default_value Default value if the referenced path is missing.
4271       *                                  Default false.
4272       * @return bool Value of boolean metadata.
4273       */
4274  	protected static function get_metadata_boolean( $data, $path, $default_value = false ) {
4275          if ( is_bool( $path ) ) {
4276              return $path;
4277          }
4278  
4279          if ( is_array( $path ) ) {
4280              $value = _wp_array_get( $data, $path );
4281              if ( null !== $value ) {
4282                  return $value;
4283              }
4284          }
4285  
4286          return $default_value;
4287      }
4288  
4289      /**
4290       * Merges new incoming data.
4291       *
4292       * @since 5.8.0
4293       * @since 5.9.0 Duotone preset also has origins.
4294       * @since 6.7.0 Replace background image objects during merge.
4295       *
4296       * @param WP_Theme_JSON $incoming Data to merge.
4297       */
4298  	public function merge( $incoming ) {
4299          $incoming_data    = $incoming->get_raw_data();
4300          $this->theme_json = array_replace_recursive( $this->theme_json, $incoming_data );
4301  
4302          /*
4303           * Recompute all the spacing sizes based on the new hierarchy of data. In the constructor
4304           * spacingScale and spacingSizes are both keyed by origin and VALID_ORIGINS is ordered, so
4305           * we can allow partial spacingScale data to inherit missing data from earlier layers when
4306           * computing the spacing sizes.
4307           *
4308           * This happens before the presets are merged to ensure that default spacing sizes can be
4309           * removed from the theme origin if $prevent_override is true.
4310           */
4311          $flattened_spacing_scale = array();
4312          foreach ( static::VALID_ORIGINS as $origin ) {
4313              $scale_path = array( 'settings', 'spacing', 'spacingScale', $origin );
4314  
4315              // Apply the base spacing scale to the current layer.
4316              $base_spacing_scale      = _wp_array_get( $this->theme_json, $scale_path, array() );
4317              $flattened_spacing_scale = array_replace( $flattened_spacing_scale, $base_spacing_scale );
4318  
4319              $spacing_scale = _wp_array_get( $incoming_data, $scale_path, null );
4320              if ( ! isset( $spacing_scale ) ) {
4321                  continue;
4322              }
4323  
4324              // Allow partial scale settings by merging with lower layers.
4325              $flattened_spacing_scale = array_replace( $flattened_spacing_scale, $spacing_scale );
4326  
4327              // Generate and merge the scales for this layer.
4328              $sizes_path           = array( 'settings', 'spacing', 'spacingSizes', $origin );
4329              $spacing_sizes        = _wp_array_get( $incoming_data, $sizes_path, array() );
4330              $spacing_scale_sizes  = static::compute_spacing_sizes( $flattened_spacing_scale );
4331              $merged_spacing_sizes = static::merge_spacing_sizes( $spacing_scale_sizes, $spacing_sizes );
4332  
4333              _wp_array_set( $incoming_data, $sizes_path, $merged_spacing_sizes );
4334          }
4335  
4336          /*
4337           * The array_replace_recursive algorithm merges at the leaf level,
4338           * but we don't want leaf arrays to be merged, so we overwrite it.
4339           *
4340           * For leaf values that are sequential arrays it will use the numeric indexes for replacement.
4341           * We rather replace the existing with the incoming value, if it exists.
4342           * This is the case of spacing.units.
4343           *
4344           * For leaf values that are associative arrays it will merge them as expected.
4345           * This is also not the behavior we want for the current associative arrays (presets).
4346           * We rather replace the existing with the incoming value, if it exists.
4347           * This happens, for example, when we merge data from theme.json upon existing
4348           * theme supports or when we merge anything coming from the same source twice.
4349           * This is the case of color.palette, color.gradients, color.duotone,
4350           * typography.fontSizes, or typography.fontFamilies.
4351           *
4352           * Additionally, for some preset types, we also want to make sure the
4353           * values they introduce don't conflict with default values. We do so
4354           * by checking the incoming slugs for theme presets and compare them
4355           * with the equivalent default presets: if a slug is present as a default
4356           * we remove it from the theme presets.
4357           */
4358          $nodes        = static::get_setting_nodes( $incoming_data );
4359          $slugs_global = static::get_default_slugs( $this->theme_json, array( 'settings' ) );
4360          foreach ( $nodes as $node ) {
4361              // Replace the spacing.units.
4362              $path   = $node['path'];
4363              $path[] = 'spacing';
4364              $path[] = 'units';
4365  
4366              $content = _wp_array_get( $incoming_data, $path, null );
4367              if ( isset( $content ) ) {
4368                  _wp_array_set( $this->theme_json, $path, $content );
4369              }
4370  
4371              // Replace the presets.
4372              foreach ( static::PRESETS_METADATA as $preset_metadata ) {
4373                  $prevent_override = $preset_metadata['prevent_override'];
4374                  if ( is_array( $prevent_override ) ) {
4375                      $global_path  = array_merge( array( 'settings' ), $prevent_override );
4376                      $global_value = _wp_array_get( $this->theme_json, $global_path, null );
4377  
4378                      $node_level_path  = array_merge( $node['path'], $prevent_override );
4379                      $prevent_override = _wp_array_get( $this->theme_json, $node_level_path, $global_value );
4380                  }
4381  
4382                  foreach ( static::VALID_ORIGINS as $origin ) {
4383                      $base_path = $node['path'];
4384                      foreach ( $preset_metadata['path'] as $leaf ) {
4385                          $base_path[] = $leaf;
4386                      }
4387  
4388                      $path   = $base_path;
4389                      $path[] = $origin;
4390  
4391                      $content = _wp_array_get( $incoming_data, $path, null );
4392                      if ( ! isset( $content ) ) {
4393                          continue;
4394                      }
4395  
4396                      // Set names for theme presets based on the slug if they are not set and can use default names.
4397                      if ( 'theme' === $origin && $preset_metadata['use_default_names'] ) {
4398                          foreach ( $content as $key => $item ) {
4399                              if ( ! isset( $item['name'] ) ) {
4400                                  $name = static::get_name_from_defaults( $item['slug'], $base_path );
4401                                  if ( null !== $name ) {
4402                                      $content[ $key ]['name'] = $name;
4403                                  }
4404                              }
4405                          }
4406                      }
4407  
4408                      // Filter out default slugs from theme presets when defaults should not be overridden.
4409                      if ( 'theme' === $origin && $prevent_override ) {
4410                          $slugs_node    = static::get_default_slugs( $this->theme_json, $node['path'] );
4411                          $preset_global = _wp_array_get( $slugs_global, $preset_metadata['path'], array() );
4412                          $preset_node   = _wp_array_get( $slugs_node, $preset_metadata['path'], array() );
4413                          $preset_slugs  = array_merge_recursive( $preset_global, $preset_node );
4414  
4415                          $content = static::filter_slugs( $content, $preset_slugs );
4416                      }
4417  
4418                      _wp_array_set( $this->theme_json, $path, $content );
4419                  }
4420              }
4421          }
4422  
4423          /*
4424           * Style values are merged at the leaf level, however
4425           * some values provide exceptions, namely style values that are
4426           * objects and represent unique definitions for the style.
4427           */
4428          $style_nodes = static::get_block_nodes(
4429              $this->theme_json,
4430              array(),
4431              array( 'include_node_paths_only' => true )
4432          );
4433  
4434          // Add top-level styles.
4435          $style_nodes[] = array( 'path' => array( 'styles' ) );
4436  
4437          foreach ( $style_nodes as $style_node ) {
4438              $path = $style_node['path'];
4439              /*
4440               * Background image styles should be replaced, not merged,
4441               * as they themselves are specific object definitions for the style.
4442               */
4443              $background_image_path = array_merge( $path, static::PROPERTIES_METADATA['background-image'] );
4444              $content               = _wp_array_get( $incoming_data, $background_image_path, null );
4445              if ( isset( $content ) ) {
4446                  _wp_array_set( $this->theme_json, $background_image_path, $content );
4447              }
4448          }
4449      }
4450  
4451      /**
4452       * Converts all filter (duotone) presets into SVGs.
4453       *
4454       * @since 5.9.1
4455       *
4456       * @param array $origins List of origins to process.
4457       * @return string SVG filters.
4458       */
4459  	public function get_svg_filters( $origins ) {
4460          $blocks_metadata = static::get_blocks_metadata();
4461          $setting_nodes   = static::get_setting_nodes( $this->theme_json, $blocks_metadata );
4462  
4463          $filters = '';
4464          foreach ( $setting_nodes as $metadata ) {
4465              $node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
4466              if ( empty( $node['color']['duotone'] ) ) {
4467                  continue;
4468              }
4469  
4470              $duotone_presets = $node['color']['duotone'];
4471  
4472              foreach ( $origins as $origin ) {
4473                  if ( ! isset( $duotone_presets[ $origin ] ) ) {
4474                      continue;
4475                  }
4476                  foreach ( $duotone_presets[ $origin ] as $duotone_preset ) {
4477                      $filters .= WP_Duotone::get_filter_svg_from_preset( $duotone_preset );
4478                  }
4479              }
4480          }
4481  
4482          return $filters;
4483      }
4484  
4485      /**
4486       * Determines whether a presets should be overridden or not.
4487       *
4488       * @since 5.9.0
4489       * @deprecated 6.0.0 Use {@see 'get_metadata_boolean'} instead.
4490       *
4491       * @param array      $theme_json The theme.json like structure to inspect.
4492       * @param array      $path       Path to inspect.
4493       * @param bool|array $override   Data to compute whether to override the preset.
4494       * @return bool|null True if the preset should override the defaults, false if not. Null if the override parameter is invalid.
4495       */
4496  	protected static function should_override_preset( $theme_json, $path, $override ) {
4497          _deprecated_function( __METHOD__, '6.0.0', 'get_metadata_boolean' );
4498  
4499          if ( is_bool( $override ) ) {
4500              return $override;
4501          }
4502  
4503          /*
4504           * The relationship between whether to override the defaults
4505           * and whether the defaults are enabled is inverse:
4506           *
4507           * - If defaults are enabled  => theme presets should not be overridden
4508           * - If defaults are disabled => theme presets should be overridden
4509           *
4510           * For example, a theme sets defaultPalette to false,
4511           * making the default palette hidden from the user.
4512           * In that case, we want all the theme presets to be present,
4513           * so they should override the defaults.
4514           */
4515          if ( is_array( $override ) ) {
4516              $value = _wp_array_get( $theme_json, array_merge( $path, $override ) );
4517              if ( isset( $value ) ) {
4518                  return ! $value;
4519              }
4520  
4521              // Search the top-level key if none was found for this node.
4522              $value = _wp_array_get( $theme_json, array_merge( array( 'settings' ), $override ) );
4523              if ( isset( $value ) ) {
4524                  return ! $value;
4525              }
4526  
4527              return true;
4528          }
4529  
4530          return null;
4531      }
4532  
4533      /**
4534       * Returns the default slugs for all the presets in an associative array
4535       * whose keys are the preset paths and the leaves is the list of slugs.
4536       *
4537       * For example:
4538       *
4539       *     array(
4540       *       'color' => array(
4541       *         'palette'   => array( 'slug-1', 'slug-2' ),
4542       *         'gradients' => array( 'slug-3', 'slug-4' ),
4543       *       ),
4544       *     )
4545       *
4546       * @since 5.9.0
4547       *
4548       * @param array $data      A theme.json like structure.
4549       * @param array $node_path The path to inspect. It's 'settings' by default.
4550       * @return array
4551       */
4552  	protected static function get_default_slugs( $data, $node_path ) {
4553          $slugs = array();
4554  
4555          foreach ( static::PRESETS_METADATA as $metadata ) {
4556              $path = $node_path;
4557              foreach ( $metadata['path'] as $leaf ) {
4558                  $path[] = $leaf;
4559              }
4560              $path[] = 'default';
4561  
4562              $preset = _wp_array_get( $data, $path, null );
4563              if ( ! isset( $preset ) ) {
4564                  continue;
4565              }
4566  
4567              $slugs_for_preset = array();
4568              foreach ( $preset as $item ) {
4569                  if ( isset( $item['slug'] ) ) {
4570                      $slugs_for_preset[] = $item['slug'];
4571                  }
4572              }
4573  
4574              _wp_array_set( $slugs, $metadata['path'], $slugs_for_preset );
4575          }
4576  
4577          return $slugs;
4578      }
4579  
4580      /**
4581       * Gets a `default`'s preset name by a provided slug.
4582       *
4583       * @since 5.9.0
4584       *
4585       * @param string $slug The slug we want to find a match from default presets.
4586       * @param array  $base_path The path to inspect. It's 'settings' by default.
4587       * @return string|null
4588       */
4589  	protected function get_name_from_defaults( $slug, $base_path ) {
4590          $path            = $base_path;
4591          $path[]          = 'default';
4592          $default_content = _wp_array_get( $this->theme_json, $path, null );
4593          if ( ! $default_content ) {
4594              return null;
4595          }
4596          foreach ( $default_content as $item ) {
4597              if ( $slug === $item['slug'] ) {
4598                  return $item['name'];
4599              }
4600          }
4601          return null;
4602      }
4603  
4604      /**
4605       * Removes the preset values whose slug is equal to any of given slugs.
4606       *
4607       * @since 5.9.0
4608       *
4609       * @param array $node  The node with the presets to validate.
4610       * @param array $slugs The slugs that should not be overridden.
4611       * @return array The new node.
4612       */
4613  	protected static function filter_slugs( $node, $slugs ) {
4614          if ( empty( $slugs ) ) {
4615              return $node;
4616          }
4617  
4618          $new_node = array();
4619          foreach ( $node as $value ) {
4620              if ( isset( $value['slug'] ) && ! in_array( $value['slug'], $slugs, true ) ) {
4621                  $new_node[] = $value;
4622              }
4623          }
4624  
4625          return $new_node;
4626      }
4627  
4628      /**
4629       * Removes insecure data from theme.json.
4630       *
4631       * @since 5.9.0
4632       * @since 6.3.2 Preserves global styles block variations when securing styles.
4633       * @since 6.6.0 Updated to allow variation element styles and $origin parameter.
4634       *
4635       * @param array  $theme_json Structure to sanitize.
4636       * @param string $origin     Optional. What source of data this object represents.
4637       *                           One of 'blocks', 'default', 'theme', or 'custom'. Default 'theme'.
4638       * @return array Sanitized structure.
4639       */
4640  	public static function remove_insecure_properties( $theme_json, $origin = 'theme' ) {
4641          if ( ! in_array( $origin, static::VALID_ORIGINS, true ) ) {
4642              $origin = 'theme';
4643          }
4644  
4645          $sanitized = array();
4646  
4647          $theme_json = WP_Theme_JSON_Schema::migrate( $theme_json, $origin );
4648  
4649          $blocks_metadata     = static::get_blocks_metadata();
4650          $valid_block_names   = array_keys( $blocks_metadata );
4651          $valid_element_names = array_keys( static::ELEMENTS );
4652          $valid_variations    = static::get_valid_block_style_variations( $blocks_metadata );
4653  
4654          $theme_json = static::sanitize( $theme_json, $valid_block_names, $valid_element_names, $valid_variations );
4655  
4656          $blocks_metadata          = static::get_blocks_metadata();
4657          $style_options            = array( 'include_block_style_variations' => true ); // Allow variations data.
4658          $style_nodes              = static::get_style_nodes( $theme_json, $blocks_metadata, $style_options );
4659          $responsive_media_queries = static::get_viewport_media_queries( $theme_json['settings']['viewport'] ?? null );
4660  
4661          foreach ( $style_nodes as $metadata ) {
4662              $input = _wp_array_get( $theme_json, $metadata['path'], array() );
4663              if ( empty( $input ) ) {
4664                  continue;
4665              }
4666  
4667              $block_name = in_array( 'blocks', $metadata['path'], true )
4668                  ? static::get_block_name_from_metadata_path( $metadata )
4669                  : null;
4670  
4671              // The global styles custom CSS is not sanitized, but can only be edited by users with 'edit_css' capability.
4672              if ( isset( $input['css'] ) && current_user_can( 'edit_css' ) ) {
4673                  $output = $input;
4674              } else {
4675                  $output = static::remove_insecure_styles( $input );
4676              }
4677  
4678              /*
4679               * Get a reference to element name from path.
4680               * $metadata['path'] = array( 'styles', 'elements', 'link' );
4681               */
4682              $current_element = $metadata['path'][ count( $metadata['path'] ) - 1 ];
4683  
4684              /*
4685               * $output is stripped of pseudo selectors. Re-add and process them
4686               * or insecure styles here.
4687               */
4688              if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) ) {
4689                  foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] as $pseudo_selector ) {
4690                      if ( isset( $input[ $pseudo_selector ] ) ) {
4691                          $output[ $pseudo_selector ] = static::remove_insecure_styles( $input[ $pseudo_selector ] );
4692                      }
4693                  }
4694              }
4695  
4696              // Re-add and process responsive breakpoint styles.
4697              foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
4698                  if ( isset( $input[ $breakpoint ] ) ) {
4699                      $output[ $breakpoint ] = static::remove_insecure_styles( $input[ $breakpoint ] );
4700  
4701                      if ( isset( $input[ $breakpoint ]['elements'] ) ) {
4702                          $output[ $breakpoint ]['elements'] = static::remove_insecure_element_styles( $input[ $breakpoint ]['elements'], $responsive_media_queries );
4703                      }
4704  
4705                      if ( isset( $input[ $breakpoint ]['blocks'] ) ) {
4706                          $output[ $breakpoint ]['blocks'] = static::remove_insecure_inner_block_styles( $input[ $breakpoint ]['blocks'], $responsive_media_queries );
4707                      }
4708  
4709                      if ( $block_name && isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_name ] ) ) {
4710                          foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_name ] as $pseudo_selector ) {
4711                              if ( isset( $input[ $breakpoint ][ $pseudo_selector ] ) ) {
4712                                  $output[ $breakpoint ][ $pseudo_selector ] = static::remove_insecure_styles( $input[ $breakpoint ][ $pseudo_selector ] );
4713                              }
4714                          }
4715                      }
4716  
4717                      // Responsive custom CSS is allowed for users with 'edit_css' capability.
4718                      if ( isset( $input[ $breakpoint ]['css'] ) && current_user_can( 'edit_css' ) ) {
4719                          $output[ $breakpoint ]['css'] = $input[ $breakpoint ]['css'];
4720                      }
4721                  }
4722              }
4723  
4724              if ( ! empty( $output ) ) {
4725                  _wp_array_set( $sanitized, $metadata['path'], $output );
4726              }
4727  
4728              if ( isset( $metadata['variations'] ) ) {
4729                  foreach ( $metadata['variations'] as $variation ) {
4730                      $variation_input = _wp_array_get( $theme_json, $variation['path'], array() );
4731                      if ( empty( $variation_input ) ) {
4732                          continue;
4733                      }
4734  
4735                      $variation_output = static::remove_insecure_styles( $variation_input );
4736  
4737                      if ( isset( $variation_input['blocks'] ) ) {
4738                          $variation_output['blocks'] = static::remove_insecure_inner_block_styles( $variation_input['blocks'], $responsive_media_queries );
4739                      }
4740  
4741                      if ( isset( $variation_input['elements'] ) ) {
4742                          $variation_output['elements'] = static::remove_insecure_element_styles( $variation_input['elements'], $responsive_media_queries );
4743                      }
4744  
4745                      // Re-add and process responsive breakpoint styles for variations.
4746                      foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
4747                          if ( isset( $variation_input[ $breakpoint ] ) ) {
4748                              $variation_output[ $breakpoint ] = static::remove_insecure_styles( $variation_input[ $breakpoint ] );
4749  
4750                              if ( isset( $variation_input[ $breakpoint ]['elements'] ) ) {
4751                                  $variation_output[ $breakpoint ]['elements'] = static::remove_insecure_element_styles( $variation_input[ $breakpoint ]['elements'], $responsive_media_queries );
4752                              }
4753  
4754                              if ( isset( $variation_input[ $breakpoint ]['blocks'] ) ) {
4755                                  $variation_output[ $breakpoint ]['blocks'] = static::remove_insecure_inner_block_styles( $variation_input[ $breakpoint ]['blocks'], $responsive_media_queries );
4756                              }
4757  
4758                              if ( $block_name && isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_name ] ) ) {
4759                                  foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_name ] as $pseudo_selector ) {
4760                                      if ( isset( $variation_input[ $breakpoint ][ $pseudo_selector ] ) ) {
4761                                          $variation_output[ $breakpoint ][ $pseudo_selector ] = static::remove_insecure_styles( $variation_input[ $breakpoint ][ $pseudo_selector ] );
4762                                      }
4763                                  }
4764                              }
4765  
4766                              // Responsive custom CSS is allowed for users with 'edit_css' capability.
4767                              if ( isset( $variation_input[ $breakpoint ]['css'] ) && current_user_can( 'edit_css' ) ) {
4768                                  $variation_output[ $breakpoint ]['css'] = $variation_input[ $breakpoint ]['css'];
4769                              }
4770                          }
4771                      }
4772  
4773                      if ( ! empty( $variation_output ) ) {
4774                          _wp_array_set( $sanitized, $variation['path'], $variation_output );
4775                      }
4776                  }
4777              }
4778          }
4779  
4780          $setting_nodes = static::get_setting_nodes( $theme_json );
4781          foreach ( $setting_nodes as $metadata ) {
4782              $input = _wp_array_get( $theme_json, $metadata['path'], array() );
4783              if ( empty( $input ) ) {
4784                  continue;
4785              }
4786  
4787              $output = static::remove_insecure_settings( $input, array( 'settings' ) === $metadata['path'] );
4788              if ( ! empty( $output ) ) {
4789                  _wp_array_set( $sanitized, $metadata['path'], $output );
4790              }
4791          }
4792  
4793          if ( empty( $sanitized['styles'] ) ) {
4794              unset( $theme_json['styles'] );
4795          } else {
4796              $theme_json['styles'] = $sanitized['styles'];
4797          }
4798  
4799          if ( empty( $sanitized['settings'] ) ) {
4800              unset( $theme_json['settings'] );
4801          } else {
4802              $theme_json['settings'] = $sanitized['settings'];
4803          }
4804  
4805          return $theme_json;
4806      }
4807  
4808      /**
4809       * Remove insecure element styles within a variation or block.
4810       *
4811       *  * When responsive media queries are provided, nested responsive state styles
4812       * matching those viewport state keys are re-added after the base sanitization pass.
4813       *
4814       * @since 6.8.0
4815       * @since 7.1.0 Added the `$responsive_media_queries` parameter.
4816       *
4817       * @param array      $elements                 The elements to process.
4818       * @param array|null $responsive_media_queries Optional. Media queries whose keys define allowed
4819       *                                             viewport states. Default null.
4820       * @return array The sanitized elements styles.
4821       */
4822  	protected static function remove_insecure_element_styles( $elements, $responsive_media_queries = null ) {
4823          $sanitized           = array();
4824          $valid_element_names = array_keys( static::ELEMENTS );
4825  
4826          foreach ( $valid_element_names as $element_name ) {
4827              $element_input = $elements[ $element_name ] ?? null;
4828              if ( $element_input ) {
4829                  $element_output = static::remove_insecure_styles( $element_input );
4830  
4831                  if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] ) ) {
4832                      foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] as $pseudo_selector ) {
4833                          if ( isset( $element_input[ $pseudo_selector ] ) ) {
4834                              $element_output[ $pseudo_selector ] = static::remove_insecure_styles( $element_input[ $pseudo_selector ] );
4835                          }
4836                      }
4837                  }
4838  
4839                  if ( null !== $responsive_media_queries ) {
4840                      // Re-add and process responsive breakpoint styles for elements.
4841                      foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
4842                          if ( isset( $element_input[ $breakpoint ] ) ) {
4843                              $element_output[ $breakpoint ] = static::remove_insecure_styles( $element_input[ $breakpoint ] );
4844  
4845                              if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] ) ) {
4846                                  foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] as $pseudo_selector ) {
4847                                      if ( isset( $element_input[ $breakpoint ][ $pseudo_selector ] ) ) {
4848                                          $element_output[ $breakpoint ][ $pseudo_selector ] = static::remove_insecure_styles( $element_input[ $breakpoint ][ $pseudo_selector ] );
4849                                      }
4850                                  }
4851                              }
4852                          }
4853                      }
4854                  }
4855  
4856                  $sanitized[ $element_name ] = $element_output;
4857              }
4858          }
4859          return $sanitized;
4860      }
4861  
4862      /**
4863       * Remove insecure styles from inner blocks and their elements.
4864       *
4865       * When responsive media queries are provided, nested responsive state styles
4866       * for those media-query keys are re-added after the base sanitization pass.
4867       *
4868       * @since 6.8.0
4869       * @since 7.1.0 Added the `$responsive_media_queries` parameter.
4870       *
4871       * @param array      $blocks                   The block styles to process.
4872       * @param array|null $responsive_media_queries Optional. Media queries whose keys define allowed
4873       *                                             viewport states. Default null.
4874       * @return array Sanitized block type styles.
4875       */
4876  	protected static function remove_insecure_inner_block_styles( $blocks, $responsive_media_queries = null ) {
4877          $sanitized = array();
4878          foreach ( $blocks as $block_type => $block_input ) {
4879              $block_output = static::remove_insecure_styles( $block_input );
4880  
4881              if ( isset( $block_input['elements'] ) ) {
4882                  $block_output['elements'] = static::remove_insecure_element_styles( $block_input['elements'], $responsive_media_queries );
4883              }
4884  
4885              if ( null !== $responsive_media_queries ) {
4886                  // Re-add and process responsive breakpoint styles for inner blocks.
4887                  foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
4888                      if ( isset( $block_input[ $breakpoint ] ) ) {
4889                          $block_output[ $breakpoint ] = static::remove_insecure_styles( $block_input[ $breakpoint ] );
4890  
4891                          if ( isset( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_type ] ) ) {
4892                              foreach ( static::VALID_BLOCK_PSEUDO_SELECTORS[ $block_type ] as $pseudo_selector ) {
4893                                  if ( isset( $block_input[ $breakpoint ][ $pseudo_selector ] ) ) {
4894                                      $block_output[ $breakpoint ][ $pseudo_selector ] = static::remove_insecure_styles( $block_input[ $breakpoint ][ $pseudo_selector ] );
4895                                  }
4896                              }
4897                          }
4898                      }
4899                  }
4900              }
4901  
4902              $sanitized[ $block_type ] = $block_output;
4903          }
4904          return $sanitized;
4905      }
4906  
4907      /**
4908       * Preserves valid typed settings from input to output based on type markers in schema.
4909       *
4910       * Recursively iterates through the schema and validates/preserves settings
4911       * that have type markers (e.g., boolean) in VALID_SETTINGS.
4912       *
4913       * @since 7.0.0
4914       *
4915       * @param array             $input  Input settings to process.
4916       * @param array             $output Output settings array (passed by reference).
4917       * @param array             $schema Schema to validate against (typically VALID_SETTINGS).
4918       * @param array<string|int> $path   Current path in the schema (for recursive calls).
4919       */
4920  	private static function preserve_valid_typed_settings( $input, &$output, $schema, $path = array() ) {
4921          foreach ( $schema as $key => $schema_value ) {
4922              $current_path = array_merge( $path, array( $key ) );
4923  
4924              // Validate boolean type markers.
4925              if ( is_bool( $schema_value ) ) {
4926                  $value = _wp_array_get( $input, $current_path, null );
4927                  if ( is_bool( $value ) ) {
4928                      _wp_array_set( $output, $current_path, $value ); // Preserve boolean value.
4929                  }
4930              } elseif ( is_array( $schema_value ) ) {
4931                  self::preserve_valid_typed_settings( $input, $output, $schema_value, $current_path ); // Recurse into nested structure.
4932              }
4933          }
4934      }
4935  
4936      /**
4937       * Processes a setting node and returns the same node
4938       * without the insecure settings.
4939       *
4940       * @since 5.9.0
4941       * @since 7.1.0 Added the `$is_root` parameter.
4942       *
4943       * @param array $input   Node to process.
4944       * @param bool  $is_root Optional. Whether the node is the root settings node. Default false.
4945       * @return array
4946       */
4947  	protected static function remove_insecure_settings( $input, $is_root = false ) {
4948          $output = array();
4949          foreach ( static::PRESETS_METADATA as $preset_metadata ) {
4950              foreach ( static::VALID_ORIGINS as $origin ) {
4951                  $path_with_origin   = $preset_metadata['path'];
4952                  $path_with_origin[] = $origin;
4953                  $presets            = _wp_array_get( $input, $path_with_origin, null );
4954                  if ( null === $presets ) {
4955                      continue;
4956                  }
4957  
4958                  $escaped_preset = array();
4959                  foreach ( $presets as $preset ) {
4960                      if (
4961                          esc_attr( esc_html( $preset['name'] ) ) === $preset['name'] &&
4962                          sanitize_html_class( $preset['slug'] ) === $preset['slug']
4963                      ) {
4964                          $value = null;
4965                          if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) {
4966                              $value = $preset[ $preset_metadata['value_key'] ];
4967                          } elseif (
4968                              isset( $preset_metadata['value_func'] ) &&
4969                              is_callable( $preset_metadata['value_func'] )
4970                          ) {
4971                              $value = call_user_func( $preset_metadata['value_func'], $preset );
4972                          }
4973  
4974                          $preset_is_valid = true;
4975                          foreach ( $preset_metadata['properties'] as $property ) {
4976                              if ( ! static::is_safe_css_declaration( $property, $value ) ) {
4977                                  $preset_is_valid = false;
4978                                  break;
4979                              }
4980                          }
4981  
4982                          if ( $preset_is_valid ) {
4983                              $escaped_preset[] = $preset;
4984                          }
4985                      }
4986                  }
4987  
4988                  if ( ! empty( $escaped_preset ) ) {
4989                      _wp_array_set( $output, $path_with_origin, $escaped_preset );
4990                  }
4991              }
4992          }
4993  
4994          // Ensure indirect properties not included in any `PRESETS_METADATA` value are allowed.
4995          static::remove_indirect_properties( $input, $output );
4996  
4997          // Preserve all valid settings that have type markers in VALID_SETTINGS.
4998          self::preserve_valid_typed_settings( $input, $output, static::VALID_SETTINGS );
4999  
5000          if ( $is_root && array_key_exists( 'viewport', $input ) ) {
5001              $output['viewport'] = static::sanitize_viewport_settings( $input['viewport'] );
5002          }
5003  
5004          return $output;
5005      }
5006  
5007      /**
5008       * Processes a style node and returns the same node
5009       * without the insecure styles.
5010       *
5011       * @since 5.9.0
5012       *
5013       * @param array $input Node to process.
5014       * @return array
5015       */
5016  	protected static function remove_insecure_styles( $input ) {
5017          $output       = array();
5018          $declarations = static::compute_style_properties( $input );
5019  
5020          foreach ( $declarations as $declaration ) {
5021              if ( static::is_safe_css_declaration( $declaration['name'], $declaration['value'] ) ) {
5022                  $path = static::PROPERTIES_METADATA[ $declaration['name'] ];
5023  
5024                  /*
5025                   * Check the value isn't an array before adding so as to not
5026                   * double up shorthand and longhand styles.
5027                   */
5028                  $value = _wp_array_get( $input, $path, array() );
5029                  if ( ! is_array( $value ) ) {
5030                      _wp_array_set( $output, $path, $value );
5031                  }
5032              }
5033          }
5034  
5035          // Ensure indirect properties not handled by `compute_style_properties` are allowed.
5036          static::remove_indirect_properties( $input, $output );
5037  
5038          return $output;
5039      }
5040  
5041      /**
5042       * Checks that a declaration provided by the user is safe.
5043       *
5044       * @since 5.9.0
5045       *
5046       * @param string $property_name  Property name in a CSS declaration, i.e. the `color` in `color: red`.
5047       * @param string $property_value Value in a CSS declaration, i.e. the `red` in `color: red`.
5048       * @return bool
5049       */
5050  	protected static function is_safe_css_declaration( $property_name, $property_value ) {
5051          $style_to_validate = $property_name . ': ' . $property_value;
5052          $filtered          = esc_html( safecss_filter_attr( $style_to_validate ) );
5053          return ! empty( trim( $filtered ) );
5054      }
5055  
5056      /**
5057       * Removes indirect properties from the given input node and
5058       * sets in the given output node.
5059       *
5060       * @since 6.2.0
5061       *
5062       * @param array $input  Node to process.
5063       * @param array $output The processed node. Passed by reference.
5064       */
5065  	private static function remove_indirect_properties( $input, &$output ) {
5066          foreach ( static::INDIRECT_PROPERTIES_METADATA as $property => $paths ) {
5067              foreach ( $paths as $path ) {
5068                  $value = _wp_array_get( $input, $path );
5069                  if (
5070                      is_string( $value ) &&
5071                      static::is_safe_css_declaration( $property, $value )
5072                  ) {
5073                      _wp_array_set( $output, $path, $value );
5074                  }
5075              }
5076          }
5077      }
5078  
5079      /**
5080       * Returns the raw data.
5081       *
5082       * @since 5.8.0
5083       *
5084       * @return array Raw data.
5085       */
5086  	public function get_raw_data() {
5087          return $this->theme_json;
5088      }
5089  
5090      /**
5091       * Transforms the given editor settings according the
5092       * add_theme_support format to the theme.json format.
5093       *
5094       * @since 5.8.0
5095       *
5096       * @param array $settings Existing editor settings.
5097       * @return array Config that adheres to the theme.json schema.
5098       */
5099  	public static function get_from_editor_settings( $settings ) {
5100          $theme_settings = array(
5101              'version'  => static::LATEST_SCHEMA,
5102              'settings' => array(),
5103          );
5104  
5105          // Deprecated theme supports.
5106          if ( isset( $settings['disableCustomColors'] ) ) {
5107              $theme_settings['settings']['color']['custom'] = ! $settings['disableCustomColors'];
5108          }
5109  
5110          if ( isset( $settings['disableCustomGradients'] ) ) {
5111              $theme_settings['settings']['color']['customGradient'] = ! $settings['disableCustomGradients'];
5112          }
5113  
5114          if ( isset( $settings['disableCustomFontSizes'] ) ) {
5115              $theme_settings['settings']['typography']['customFontSize'] = ! $settings['disableCustomFontSizes'];
5116          }
5117  
5118          if ( isset( $settings['enableCustomLineHeight'] ) ) {
5119              $theme_settings['settings']['typography']['lineHeight'] = $settings['enableCustomLineHeight'];
5120          }
5121  
5122          if ( isset( $settings['enableCustomUnits'] ) ) {
5123              $theme_settings['settings']['spacing']['units'] = ( true === $settings['enableCustomUnits'] ) ?
5124                  array( 'px', 'em', 'rem', 'vh', 'vw', '%' ) :
5125                  $settings['enableCustomUnits'];
5126          }
5127  
5128          if ( isset( $settings['colors'] ) ) {
5129              $theme_settings['settings']['color']['palette'] = $settings['colors'];
5130          }
5131  
5132          if ( isset( $settings['gradients'] ) ) {
5133              $theme_settings['settings']['color']['gradients'] = $settings['gradients'];
5134          }
5135  
5136          if ( isset( $settings['fontSizes'] ) ) {
5137              $font_sizes = $settings['fontSizes'];
5138              // Back-compatibility for presets without units.
5139              foreach ( $font_sizes as $key => $font_size ) {
5140                  if ( is_numeric( $font_size['size'] ) ) {
5141                      $font_sizes[ $key ]['size'] = $font_size['size'] . 'px';
5142                  }
5143              }
5144              $theme_settings['settings']['typography']['fontSizes'] = $font_sizes;
5145          }
5146  
5147          if ( isset( $settings['enableCustomSpacing'] ) ) {
5148              $theme_settings['settings']['spacing']['padding'] = $settings['enableCustomSpacing'];
5149          }
5150  
5151          if ( isset( $settings['spacingSizes'] ) ) {
5152              $theme_settings['settings']['spacing']['spacingSizes'] = $settings['spacingSizes'];
5153          }
5154  
5155          return $theme_settings;
5156      }
5157  
5158      /**
5159       * Returns the current theme's wanted patterns(slugs) to be
5160       * registered from Pattern Directory.
5161       *
5162       * @since 6.0.0
5163       *
5164       * @return string[]
5165       */
5166  	public function get_patterns() {
5167          if ( isset( $this->theme_json['patterns'] ) && is_array( $this->theme_json['patterns'] ) ) {
5168              return $this->theme_json['patterns'];
5169          }
5170          return array();
5171      }
5172  
5173      /**
5174       * Returns a valid theme.json as provided by a theme.
5175       *
5176       * Unlike get_raw_data() this returns the presets flattened, as provided by a theme.
5177       * This also uses appearanceTools instead of their opt-ins if all of them are true.
5178       *
5179       * @since 6.0.0
5180       *
5181       * @return array
5182       */
5183  	public function get_data() {
5184          $output = $this->theme_json;
5185          $nodes  = static::get_setting_nodes( $output );
5186  
5187          /**
5188           * Flatten the theme & custom origins into a single one.
5189           *
5190           * For example, the following:
5191           *
5192           * {
5193           *   "settings": {
5194           *     "color": {
5195           *       "palette": {
5196           *         "theme": [ {} ],
5197           *         "custom": [ {} ]
5198           *       }
5199           *     }
5200           *   }
5201           * }
5202           *
5203           * will be converted to:
5204           *
5205           * {
5206           *   "settings": {
5207           *     "color": {
5208           *       "palette": [ {} ]
5209           *     }
5210           *   }
5211           * }
5212           */
5213          foreach ( $nodes as $node ) {
5214              foreach ( static::PRESETS_METADATA as $preset_metadata ) {
5215                  $path = $node['path'];
5216                  foreach ( $preset_metadata['path'] as $preset_metadata_path ) {
5217                      $path[] = $preset_metadata_path;
5218                  }
5219                  $preset = _wp_array_get( $output, $path, null );
5220                  if ( null === $preset ) {
5221                      continue;
5222                  }
5223  
5224                  $items = array();
5225                  if ( isset( $preset['theme'] ) ) {
5226                      foreach ( $preset['theme'] as $item ) {
5227                          $slug = $item['slug'];
5228                          unset( $item['slug'] );
5229                          $items[ $slug ] = $item;
5230                      }
5231                  }
5232                  if ( isset( $preset['custom'] ) ) {
5233                      foreach ( $preset['custom'] as $item ) {
5234                          $slug = $item['slug'];
5235                          unset( $item['slug'] );
5236                          $items[ $slug ] = $item;
5237                      }
5238                  }
5239                  $flattened_preset = array();
5240                  foreach ( $items as $slug => $value ) {
5241                      $flattened_preset[] = array_merge( array( 'slug' => (string) $slug ), $value );
5242                  }
5243                  _wp_array_set( $output, $path, $flattened_preset );
5244              }
5245          }
5246  
5247          /*
5248           * If all of the static::APPEARANCE_TOOLS_OPT_INS are true,
5249           * this code unsets them and sets 'appearanceTools' instead.
5250           */
5251          foreach ( $nodes as $node ) {
5252              $all_opt_ins_are_set = true;
5253              foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) {
5254                  $full_path = $node['path'];
5255                  foreach ( $opt_in_path as $opt_in_path_item ) {
5256                      $full_path[] = $opt_in_path_item;
5257                  }
5258                  /*
5259                   * Use "unset prop" as a marker instead of "null" because
5260                   * "null" can be a valid value for some props (e.g. blockGap).
5261                   */
5262                  $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' );
5263                  if ( 'unset prop' === $opt_in_value ) {
5264                      $all_opt_ins_are_set = false;
5265                      break;
5266                  }
5267              }
5268  
5269              if ( $all_opt_ins_are_set ) {
5270                  $node_path_with_appearance_tools   = $node['path'];
5271                  $node_path_with_appearance_tools[] = 'appearanceTools';
5272                  _wp_array_set( $output, $node_path_with_appearance_tools, true );
5273                  foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) {
5274                      $full_path = $node['path'];
5275                      foreach ( $opt_in_path as $opt_in_path_item ) {
5276                          $full_path[] = $opt_in_path_item;
5277                      }
5278                      /*
5279                       * Use "unset prop" as a marker instead of "null" because
5280                       * "null" can be a valid value for some props (e.g. blockGap).
5281                       */
5282                      $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' );
5283                      if ( true !== $opt_in_value ) {
5284                          continue;
5285                      }
5286  
5287                      /*
5288                       * The following could be improved to be path independent.
5289                       * At the moment it relies on a couple of assumptions:
5290                       *
5291                       * - all opt-ins having a path of size 2.
5292                       * - there's two sources of settings: the top-level and the block-level.
5293                       */
5294                      if (
5295                          ( 1 === count( $node['path'] ) ) &&
5296                          ( 'settings' === $node['path'][0] )
5297                      ) {
5298                          // Top-level settings.
5299                          unset( $output['settings'][ $opt_in_path[0] ][ $opt_in_path[1] ] );
5300                          if ( empty( $output['settings'][ $opt_in_path[0] ] ) ) {
5301                              unset( $output['settings'][ $opt_in_path[0] ] );
5302                          }
5303                      } elseif (
5304                          ( 3 === count( $node['path'] ) ) &&
5305                          ( 'settings' === $node['path'][0] ) &&
5306                          ( 'blocks' === $node['path'][1] )
5307                      ) {
5308                          // Block-level settings.
5309                          $block_name = $node['path'][2];
5310                          unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ][ $opt_in_path[1] ] );
5311                          if ( empty( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] ) ) {
5312                              unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] );
5313                          }
5314                      }
5315                  }
5316              }
5317          }
5318  
5319          wp_recursive_ksort( $output );
5320  
5321          return $output;
5322      }
5323  
5324      /**
5325       * Sets the spacingSizes array based on the spacingScale values from theme.json.
5326       *
5327       * @since 6.1.0
5328       * @deprecated 6.6.0 No longer used as the spacingSizes are automatically
5329       *                   generated in the constructor and merge methods instead
5330       *                   of manually after instantiation.
5331       *
5332       * @return void
5333       */
5334  	public function set_spacing_sizes() {
5335          _deprecated_function( __METHOD__, '6.6.0' );
5336  
5337          $spacing_scale = $this->theme_json['settings']['spacing']['spacingScale'] ?? array();
5338  
5339          if ( ! isset( $spacing_scale['steps'] )
5340              || ! is_numeric( $spacing_scale['steps'] )
5341              || ! isset( $spacing_scale['mediumStep'] )
5342              || ! isset( $spacing_scale['unit'] )
5343              || ! isset( $spacing_scale['operator'] )
5344              || ! isset( $spacing_scale['increment'] )
5345              || ! isset( $spacing_scale['steps'] )
5346              || ! is_numeric( $spacing_scale['increment'] )
5347              || ! is_numeric( $spacing_scale['mediumStep'] )
5348              || ( '+' !== $spacing_scale['operator'] && '*' !== $spacing_scale['operator'] ) ) {
5349              if ( ! empty( $spacing_scale ) ) {
5350                  wp_trigger_error(
5351                      __METHOD__,
5352                      sprintf(
5353                          /* translators: 1: theme.json, 2: settings.spacing.spacingScale */
5354                          __( 'Some of the %1$s %2$s values are invalid' ),
5355                          'theme.json',
5356                          'settings.spacing.spacingScale'
5357                      ),
5358                      E_USER_NOTICE
5359                  );
5360              }
5361              return;
5362          }
5363  
5364          // If theme authors want to prevent the generation of the core spacing scale they can set their theme.json spacingScale.steps to 0.
5365          if ( 0 === $spacing_scale['steps'] ) {
5366              return;
5367          }
5368  
5369          $spacing_sizes = static::compute_spacing_sizes( $spacing_scale );
5370  
5371          // If there are 7 or fewer steps in the scale revert to numbers for labels instead of t-shirt sizes.
5372          if ( $spacing_scale['steps'] <= 7 ) {
5373              for ( $spacing_sizes_count = 0; $spacing_sizes_count < count( $spacing_sizes ); $spacing_sizes_count++ ) {
5374                  $spacing_sizes[ $spacing_sizes_count ]['name'] = (string) ( $spacing_sizes_count + 1 );
5375              }
5376          }
5377  
5378          _wp_array_set( $this->theme_json, array( 'settings', 'spacing', 'spacingSizes', 'default' ), $spacing_sizes );
5379      }
5380  
5381      /**
5382       * Merges two sets of spacing size presets.
5383       *
5384       * @since 6.6.0
5385       *
5386       * @param array $base     The base set of spacing sizes.
5387       * @param array $incoming The set of spacing sizes to merge with the base. Duplicate slugs will override the base values.
5388       * @return array The merged set of spacing sizes.
5389       */
5390  	private static function merge_spacing_sizes( $base, $incoming ) {
5391          // Preserve the order if there are no base (spacingScale) values.
5392          if ( empty( $base ) ) {
5393              return $incoming;
5394          }
5395          $merged = array();
5396          foreach ( $base as $item ) {
5397              $merged[ $item['slug'] ] = $item;
5398          }
5399          foreach ( $incoming as $item ) {
5400              $merged[ $item['slug'] ] = $item;
5401          }
5402          ksort( $merged, SORT_NUMERIC );
5403          return array_values( $merged );
5404      }
5405  
5406      /**
5407       * Generates a set of spacing sizes by starting with a medium size and
5408       * applying an operator with an increment value to generate the rest of the
5409       * sizes outward from the medium size. The medium slug is '50' with the rest
5410       * of the slugs being 10 apart. The generated names use t-shirt sizing.
5411       *
5412       * Example:
5413       *
5414       *     $spacing_scale = array(
5415       *         'steps'      => 4,
5416       *         'mediumStep' => 16,
5417       *         'unit'       => 'px',
5418       *         'operator'   => '+',
5419       *         'increment'  => 2,
5420       *     );
5421       *     $spacing_sizes = static::compute_spacing_sizes( $spacing_scale );
5422       *     // -> array(
5423       *     //        array( 'name' => 'Small',   'slug' => '40', 'size' => '14px' ),
5424       *     //        array( 'name' => 'Medium',  'slug' => '50', 'size' => '16px' ),
5425       *     //        array( 'name' => 'Large',   'slug' => '60', 'size' => '18px' ),
5426       *     //        array( 'name' => 'X-Large', 'slug' => '70', 'size' => '20px' ),
5427       *     //    )
5428       *
5429       * @since 6.6.0
5430       *
5431       * @param array $spacing_scale {
5432       *      The spacing scale values. All are required.
5433       *
5434       *      @type int    $steps      The number of steps in the scale. (up to 10 steps are supported.)
5435       *      @type float  $mediumStep The middle value that gets the slug '50'. (For even number of steps, this becomes the first middle value.)
5436       *      @type string $unit       The CSS unit to use for the sizes.
5437       *      @type string $operator   The mathematical operator to apply to generate the other sizes. Either '+' or '*'.
5438       *      @type float  $increment  The value used with the operator to generate the other sizes.
5439       * }
5440       * @return array The spacing sizes presets or an empty array if some spacing scale values are missing or invalid.
5441       */
5442  	private static function compute_spacing_sizes( $spacing_scale ) {
5443          /*
5444           * This condition is intentionally missing some checks on ranges for the values in order to
5445           * keep backwards compatibility with the previous implementation.
5446           */
5447          if (
5448              ! isset( $spacing_scale['steps'] ) ||
5449              ! is_numeric( $spacing_scale['steps'] ) ||
5450              0 === $spacing_scale['steps'] ||
5451              ! isset( $spacing_scale['mediumStep'] ) ||
5452              ! is_numeric( $spacing_scale['mediumStep'] ) ||
5453              ! isset( $spacing_scale['unit'] ) ||
5454              ! isset( $spacing_scale['operator'] ) ||
5455              ( '+' !== $spacing_scale['operator'] && '*' !== $spacing_scale['operator'] ) ||
5456              ! isset( $spacing_scale['increment'] ) ||
5457              ! is_numeric( $spacing_scale['increment'] )
5458          ) {
5459              return array();
5460          }
5461  
5462          $unit            = '%' === $spacing_scale['unit'] ? '%' : sanitize_title( $spacing_scale['unit'] );
5463          $current_step    = $spacing_scale['mediumStep'];
5464          $steps_mid_point = round( $spacing_scale['steps'] / 2, 0 );
5465          $x_small_count   = null;
5466          $below_sizes     = array();
5467          $slug            = 40;
5468          $remainder       = 0;
5469  
5470          for ( $below_midpoint_count = $steps_mid_point - 1; $spacing_scale['steps'] > 1 && $slug > 0 && $below_midpoint_count > 0; $below_midpoint_count-- ) {
5471              if ( '+' === $spacing_scale['operator'] ) {
5472                  $current_step -= $spacing_scale['increment'];
5473              } elseif ( $spacing_scale['increment'] > 1 ) {
5474                  $current_step /= $spacing_scale['increment'];
5475              } else {
5476                  $current_step *= $spacing_scale['increment'];
5477              }
5478  
5479              if ( $current_step <= 0 ) {
5480                  $remainder = $below_midpoint_count;
5481                  break;
5482              }
5483  
5484              $below_sizes[] = array(
5485                  /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Small. */
5486                  'name' => $below_midpoint_count === $steps_mid_point - 1 ? __( 'Small' ) : sprintf( __( '%sX-Small' ), (string) $x_small_count ),
5487                  'slug' => (string) $slug,
5488                  'size' => round( $current_step, 2 ) . $unit,
5489              );
5490  
5491              if ( $below_midpoint_count === $steps_mid_point - 2 ) {
5492                  $x_small_count = 2;
5493              }
5494  
5495              if ( $below_midpoint_count < $steps_mid_point - 2 ) {
5496                  ++$x_small_count;
5497              }
5498  
5499              $slug -= 10;
5500          }
5501  
5502          $below_sizes = array_reverse( $below_sizes );
5503  
5504          $below_sizes[] = array(
5505              'name' => __( 'Medium' ),
5506              'slug' => '50',
5507              'size' => $spacing_scale['mediumStep'] . $unit,
5508          );
5509  
5510          $current_step  = $spacing_scale['mediumStep'];
5511          $x_large_count = null;
5512          $above_sizes   = array();
5513          $slug          = 60;
5514          $steps_above   = ( $spacing_scale['steps'] - $steps_mid_point ) + $remainder;
5515  
5516          for ( $above_midpoint_count = 0; $above_midpoint_count < $steps_above; $above_midpoint_count++ ) {
5517              $current_step = '+' === $spacing_scale['operator']
5518                  ? $current_step + $spacing_scale['increment']
5519                  : ( $spacing_scale['increment'] >= 1 ? $current_step * $spacing_scale['increment'] : $current_step / $spacing_scale['increment'] );
5520  
5521              $above_sizes[] = array(
5522                  /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Large. */
5523                  'name' => 0 === $above_midpoint_count ? __( 'Large' ) : sprintf( __( '%sX-Large' ), (string) $x_large_count ),
5524                  'slug' => (string) $slug,
5525                  'size' => round( $current_step, 2 ) . $unit,
5526              );
5527  
5528              if ( 1 === $above_midpoint_count ) {
5529                  $x_large_count = 2;
5530              }
5531  
5532              if ( $above_midpoint_count > 1 ) {
5533                  ++$x_large_count;
5534              }
5535  
5536              $slug += 10;
5537          }
5538  
5539          $spacing_sizes = $below_sizes;
5540          foreach ( $above_sizes as $above_sizes_item ) {
5541              $spacing_sizes[] = $above_sizes_item;
5542          }
5543  
5544          return $spacing_sizes;
5545      }
5546  
5547      /**
5548       * This is used to convert the internal representation of variables to the CSS representation.
5549       * For example, `var:preset|color|vivid-green-cyan` becomes `var(--wp--preset--color--vivid-green-cyan)`.
5550       *
5551       * @since 6.3.0
5552       *
5553       * @param string $value The variable such as var:preset|color|vivid-green-cyan to convert.
5554       * @return string The converted variable.
5555       */
5556  	private static function convert_custom_properties( $value ) {
5557          $prefix     = 'var:';
5558          $prefix_len = strlen( $prefix );
5559          $token_in   = '|';
5560          $token_out  = '--';
5561          if ( str_starts_with( $value, $prefix ) ) {
5562              $unwrapped_name = str_replace(
5563                  $token_in,
5564                  $token_out,
5565                  substr( $value, $prefix_len )
5566              );
5567              $value          = "var(--wp--$unwrapped_name)";
5568          }
5569  
5570          return $value;
5571      }
5572  
5573      /**
5574       * Given a tree, converts the internal representation of variables to the CSS representation.
5575       * It is recursive and modifies the input in-place.
5576       *
5577       * @since 6.3.0
5578       *
5579       * @param array $tree Input to process.
5580       * @return array The modified $tree.
5581       */
5582  	private static function resolve_custom_css_format( $tree ) {
5583          $prefix = 'var:';
5584  
5585          foreach ( $tree as $key => $data ) {
5586              if ( is_string( $data ) && str_starts_with( $data, $prefix ) ) {
5587                  $tree[ $key ] = self::convert_custom_properties( $data );
5588              } elseif ( is_array( $data ) ) {
5589                  $tree[ $key ] = self::resolve_custom_css_format( $data );
5590              }
5591          }
5592  
5593          return $tree;
5594      }
5595  
5596      /**
5597       * Returns the selectors metadata for a block.
5598       *
5599       * @since 6.3.0
5600       *
5601       * @param object $block_type    The block type.
5602       * @param string $root_selector The block's root selector.
5603       * @return array The custom selectors set by the block.
5604       */
5605  	protected static function get_block_selectors( $block_type, $root_selector ) {
5606          if ( ! empty( $block_type->selectors ) ) {
5607              return $block_type->selectors;
5608          }
5609  
5610          $selectors = array( 'root' => $root_selector );
5611          foreach ( static::BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS as $key => $feature ) {
5612              $feature_selector = wp_get_block_css_selector( $block_type, $key );
5613              if ( null !== $feature_selector ) {
5614                  $selectors[ $feature ] = array( 'root' => $feature_selector );
5615              }
5616          }
5617  
5618          return $selectors;
5619      }
5620  
5621      /**
5622       * Generates all the element selectors for a block.
5623       *
5624       * @since 6.3.0
5625       *
5626       * @param string $root_selector The block's root CSS selector.
5627       * @return array The block's element selectors.
5628       */
5629  	protected static function get_block_element_selectors( $root_selector ) {
5630          /*
5631           * Assign defaults, then override those that the block sets by itself.
5632           * If the block selector is compounded, will append the element to each
5633           * individual block selector.
5634           */
5635          $block_selectors   = explode( ',', $root_selector );
5636          $element_selectors = array();
5637          foreach ( static::ELEMENTS as $el_name => $el_selector ) {
5638              $element_selector = array();
5639              foreach ( $block_selectors as $selector ) {
5640                  if ( $selector === $el_selector ) {
5641                      $element_selector = array( $el_selector );
5642                      break;
5643                  }
5644                  $element_selector[] = static::prepend_to_selector( $el_selector, $selector . ' ' );
5645              }
5646              $element_selectors[ $el_name ] = implode( ',', $element_selector );
5647          }
5648  
5649          return $element_selectors;
5650      }
5651  
5652      /**
5653       * Generates style declarations for a node's features e.g., color, border,
5654       * typography etc. that have custom selectors in their related block's
5655       * metadata.
5656       *
5657       * @since 6.3.0
5658       *
5659       * @param object $metadata The related block metadata containing selectors.
5660       * @param object $node     A merged theme.json node for block or variation.
5661       * @return array The style declarations for the node's features with custom
5662       *               selectors.
5663       */
5664  	protected function get_feature_declarations_for_node( $metadata, &$node ) {
5665          $declarations = array();
5666  
5667          if ( ! isset( $metadata['selectors'] ) ) {
5668              return $declarations;
5669          }
5670  
5671          $settings = $this->theme_json['settings'] ?? array();
5672  
5673          foreach ( $metadata['selectors'] as $feature => $feature_selectors ) {
5674              /*
5675               * Skip if this is the block's root selector, the custom CSS
5676               * selector, or the block doesn't have any styles for the feature.
5677               */
5678              if ( 'root' === $feature || 'css' === $feature || empty( $node[ $feature ] ) ) {
5679                  continue;
5680              }
5681  
5682              if ( is_array( $feature_selectors ) ) {
5683                  foreach ( $feature_selectors as $subfeature => $subfeature_selector ) {
5684                      if ( 'root' === $subfeature || empty( $node[ $feature ][ $subfeature ] ) ) {
5685                          continue;
5686                      }
5687  
5688                      /*
5689                       * Create temporary node containing only the subfeature data
5690                       * to leverage existing `compute_style_properties` function.
5691                       */
5692                      $subfeature_node = array(
5693                          $feature => array(
5694                              $subfeature => $node[ $feature ][ $subfeature ],
5695                          ),
5696                      );
5697  
5698                      // Generate style declarations.
5699                      $new_declarations = static::compute_style_properties( $subfeature_node, $settings, null, $this->theme_json );
5700  
5701                      // Merge subfeature declarations into feature declarations.
5702                      if ( isset( $declarations[ $subfeature_selector ] ) ) {
5703                          foreach ( $new_declarations as $new_declaration ) {
5704                              $declarations[ $subfeature_selector ][] = $new_declaration;
5705                          }
5706                      } else {
5707                          $declarations[ $subfeature_selector ] = $new_declarations;
5708                      }
5709  
5710                      /*
5711                       * Remove the subfeature from the block's node now its
5712                       * styles will be included under its own selector not the
5713                       * block's.
5714                       */
5715                      unset( $node[ $feature ][ $subfeature ] );
5716                  }
5717              }
5718  
5719              /*
5720               * Now subfeatures have been processed and removed we can process
5721               * feature root selector or simple string selector.
5722               */
5723              if (
5724                  is_string( $feature_selectors ) ||
5725                  ( isset( $feature_selectors['root'] ) && $feature_selectors['root'] )
5726              ) {
5727                  $feature_selector = is_string( $feature_selectors ) ? $feature_selectors : $feature_selectors['root'];
5728  
5729                  /*
5730                   * Create temporary node containing only the feature data
5731                   * to leverage existing `compute_style_properties` function.
5732                   */
5733                  $feature_node = array( $feature => $node[ $feature ] );
5734  
5735                  // Generate the style declarations.
5736                  $new_declarations = static::compute_style_properties( $feature_node, $settings, null, $this->theme_json );
5737  
5738                  /*
5739                   * Merge new declarations with any that already exist for
5740                   * the feature selector. This may occur when multiple block
5741                   * support features use the same custom selector.
5742                   */
5743                  if ( isset( $declarations[ $feature_selector ] ) ) {
5744                      foreach ( $new_declarations as $new_declaration ) {
5745                          $declarations[ $feature_selector ][] = $new_declaration;
5746                      }
5747                  } else {
5748                      $declarations[ $feature_selector ] = $new_declarations;
5749                  }
5750  
5751                  /*
5752                   * Remove the feature from the block's node now its styles
5753                   * will be included under its own selector not the block's.
5754                   */
5755                  unset( $node[ $feature ] );
5756              }
5757          }
5758  
5759          return $declarations;
5760      }
5761  
5762      /**
5763       * Replaces CSS variables with their values in place.
5764       *
5765       * @since 6.3.0
5766       * @since 6.5.0 Check for empty style before processing its value.
5767       *
5768       * @param array $styles CSS declarations to convert.
5769       * @param array $values key => value pairs to use for replacement.
5770       * @return array
5771       */
5772  	private static function convert_variables_to_value( $styles, $values ) {
5773          foreach ( $styles as $key => $style ) {
5774              if ( empty( $style ) ) {
5775                  continue;
5776              }
5777  
5778              if ( is_array( $style ) ) {
5779                  $styles[ $key ] = self::convert_variables_to_value( $style, $values );
5780                  continue;
5781              }
5782  
5783              if ( 0 <= strpos( $style, 'var(' ) ) {
5784                  // find all the variables in the string in the form of var(--variable-name, fallback), with fallback in the second capture group.
5785  
5786                  $has_matches = preg_match_all( '/var\(([^),]+)?,?\s?(\S+)?\)/', $style, $var_parts );
5787  
5788                  if ( $has_matches ) {
5789                      $resolved_style = $styles[ $key ];
5790                      foreach ( $var_parts[1] as $index => $var_part ) {
5791                          $key_in_values   = 'var(' . $var_part . ')';
5792                          $rule_to_replace = $var_parts[0][ $index ]; // the css rule to replace e.g. var(--wp--preset--color--vivid-green-cyan).
5793                          $fallback        = $var_parts[2][ $index ]; // the fallback value.
5794                          $resolved_style  = str_replace(
5795                              array(
5796                                  $rule_to_replace,
5797                                  $fallback,
5798                              ),
5799                              array(
5800                                  $values[ $key_in_values ] ?? $rule_to_replace,
5801                                  $values[ $fallback ] ?? $fallback,
5802                              ),
5803                              $resolved_style
5804                          );
5805                      }
5806                      $styles[ $key ] = $resolved_style;
5807                  }
5808              }
5809          }
5810  
5811          return $styles;
5812      }
5813  
5814      /**
5815       * Resolves the values of CSS variables in the given styles.
5816       *
5817       * @since 6.3.0
5818       *
5819       * @param WP_Theme_JSON $theme_json The theme json resolver.
5820       * @return WP_Theme_JSON The $theme_json with resolved variables.
5821       */
5822  	public static function resolve_variables( $theme_json ) {
5823          $settings    = $theme_json->get_settings();
5824          $styles      = $theme_json->get_raw_data()['styles'];
5825          $preset_vars = static::compute_preset_vars( $settings, static::VALID_ORIGINS );
5826          $theme_vars  = static::compute_theme_vars( $settings );
5827          $vars        = array_reduce(
5828              array_merge( $preset_vars, $theme_vars ),
5829              function ( $carry, $item ) {
5830                  $name                    = $item['name'];
5831                  $carry[ "var({$name})" ] = $item['value'];
5832                  return $carry;
5833              },
5834              array()
5835          );
5836  
5837          $theme_json->theme_json['styles'] = self::convert_variables_to_value( $styles, $vars );
5838          return $theme_json;
5839      }
5840  
5841      /**
5842       * Generates a selector for a block style variation.
5843       *
5844       * @since 6.5.0
5845       *
5846       * @param string $variation_name Name of the block style variation.
5847       * @param string $block_selector CSS selector for the block.
5848       * @return string Block selector with block style variation selector added to it.
5849       */
5850  	protected static function get_block_style_variation_selector( $variation_name, $block_selector ) {
5851          $variation_class = ".is-style-$variation_name";
5852  
5853          if ( ! $block_selector ) {
5854              return $variation_class;
5855          }
5856  
5857          $limit          = 1;
5858          $selector_parts = static::split_selector_list( $block_selector );
5859          $result         = array();
5860  
5861          /*
5862           * Append the variation class to each selector's ancestor: the first
5863           * run of characters before any combinator (whitespace) or pseudo-class
5864           * (`:`). Only the first match is replaced.
5865           *
5866           * Examples ("custom" variation):
5867           * - `.wp-block`              => `.wp-block.is-style-custom`
5868           * - `.wp-block .inner`       => `.wp-block.is-style-custom .inner`
5869           * - `.wp-block:where(.a .b)` => `.wp-block.is-style-custom:where(.a .b)`
5870           * - `:where(.outer .inner)`  => `:where(.outer.is-style-custom .inner)`
5871           */
5872          foreach ( $selector_parts as $part ) {
5873              $result[] = preg_replace_callback(
5874                  '/[^\s:]+/',
5875                  function ( $matches ) use ( $variation_class ) {
5876                      return $matches[0] . $variation_class;
5877                  },
5878                  $part,
5879                  $limit
5880              );
5881          }
5882  
5883          return implode( ', ', $result );
5884      }
5885  
5886      /**
5887       * Applies a block style variation class to a feature selector.
5888       *
5889       * Feature selectors can target a different element than the block's root
5890       * selector. For example, the Button block's root selector targets the inner
5891       * link, while its dimensions width selector targets the outer wrapper. Apply
5892       * the variation class directly to the selector that will receive the
5893       * declarations instead of deriving it by subtracting the root selector from
5894       * the feature selector.
5895       *
5896       * @since 7.0.0
5897       *
5898       * @param array  $style_variation Style variation metadata.
5899       * @param string $feature_selector CSS selector for the feature.
5900       * @return string Feature selector with block style variation selector added.
5901       */
5902  	protected static function get_block_style_variation_feature_selector( $style_variation, $feature_selector ) {
5903          $variation_path = $style_variation['path'] ?? array();
5904          $variation_name = $style_variation['name'] ?? ( is_array( $variation_path ) ? end( $variation_path ) : null );
5905  
5906          if ( ! $variation_name ) {
5907              return $style_variation['selector'] ?? $feature_selector;
5908          }
5909  
5910          $variation_class = ".is-style-$variation_name";
5911          $selector_parts  = static::split_selector_list( $feature_selector );
5912          $selector_parts  = array_map(
5913              static function ( $selector ) use ( $variation_class ) {
5914                  $prefix = $variation_class . ' ';
5915  
5916                  if ( str_starts_with( $selector, $prefix ) ) {
5917                      return substr( $selector, strlen( $prefix ) );
5918                  }
5919  
5920                  return $selector;
5921              },
5922              $selector_parts
5923          );
5924  
5925          return static::get_block_style_variation_selector(
5926              $variation_name,
5927              implode( ', ', $selector_parts )
5928          );
5929      }
5930  
5931      /**
5932       * Collects valid block style variations keyed by block type.
5933       *
5934       * @since 6.6.0
5935       * @since 6.8.0 Added the `$blocks_metadata` parameter.
5936       *
5937       * @param array $blocks_metadata Optional. List of metadata per block. Default is the metadata for all blocks.
5938       * @return array Valid block style variations by block type.
5939       */
5940  	protected static function get_valid_block_style_variations( $blocks_metadata = array() ) {
5941          $valid_variations = array();
5942          $blocks_metadata  = empty( $blocks_metadata ) ? static::get_blocks_metadata() : $blocks_metadata;
5943          foreach ( $blocks_metadata as $block_name => $block_meta ) {
5944              if ( ! isset( $block_meta['styleVariations'] ) ) {
5945                  continue;
5946              }
5947              $valid_variations[ $block_name ] = array_keys( $block_meta['styleVariations'] );
5948          }
5949  
5950          return $valid_variations;
5951      }
5952  
5953      /**
5954       * Extracts the block name from the block metadata path.
5955       *
5956       * @since 7.1.0
5957       *
5958       * @param array $block_metadata Block metadata.
5959       * @return string|null The block name or null if not found.
5960       */
5961  	private static function get_block_name_from_metadata_path( $block_metadata ) {
5962          return $block_metadata['path'][2] ?? null;
5963      }
5964  }


Generated : Thu Jul 16 08:20:16 2026 Cross-referenced by PHPXref