[ 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       * @var array
 130       */
 131      const PRESETS_METADATA = array(
 132          array(
 133              'path'              => array( 'dimensions', 'aspectRatios' ),
 134              'prevent_override'  => array( 'dimensions', 'defaultAspectRatios' ),
 135              'use_default_names' => false,
 136              'value_key'         => 'ratio',
 137              'css_vars'          => '--wp--preset--aspect-ratio--$slug',
 138              'classes'           => array(),
 139              'properties'        => array( 'aspect-ratio' ),
 140          ),
 141          array(
 142              'path'              => array( 'color', 'palette' ),
 143              'prevent_override'  => array( 'color', 'defaultPalette' ),
 144              'use_default_names' => false,
 145              'value_key'         => 'color',
 146              'css_vars'          => '--wp--preset--color--$slug',
 147              'classes'           => array(
 148                  '.has-$slug-color'            => 'color',
 149                  '.has-$slug-background-color' => 'background-color',
 150                  '.has-$slug-border-color'     => 'border-color',
 151              ),
 152              'properties'        => array( 'color', 'background-color', 'border-color' ),
 153          ),
 154          array(
 155              'path'              => array( 'color', 'gradients' ),
 156              'prevent_override'  => array( 'color', 'defaultGradients' ),
 157              'use_default_names' => false,
 158              'value_key'         => 'gradient',
 159              'css_vars'          => '--wp--preset--gradient--$slug',
 160              'classes'           => array( '.has-$slug-gradient-background' => 'background' ),
 161              'properties'        => array( 'background' ),
 162          ),
 163          array(
 164              'path'              => array( 'color', 'duotone' ),
 165              'prevent_override'  => array( 'color', 'defaultDuotone' ),
 166              'use_default_names' => false,
 167              'value_func'        => null, // CSS Custom Properties for duotone are handled by block supports in class-wp-duotone.php.
 168              'css_vars'          => null,
 169              'classes'           => array(),
 170              'properties'        => array( 'filter' ),
 171          ),
 172          array(
 173              'path'              => array( 'typography', 'fontSizes' ),
 174              'prevent_override'  => array( 'typography', 'defaultFontSizes' ),
 175              'use_default_names' => true,
 176              'value_func'        => 'wp_get_typography_font_size_value',
 177              'css_vars'          => '--wp--preset--font-size--$slug',
 178              'classes'           => array( '.has-$slug-font-size' => 'font-size' ),
 179              'properties'        => array( 'font-size' ),
 180          ),
 181          array(
 182              'path'              => array( 'typography', 'fontFamilies' ),
 183              'prevent_override'  => false,
 184              'use_default_names' => false,
 185              'value_key'         => 'fontFamily',
 186              'css_vars'          => '--wp--preset--font-family--$slug',
 187              'classes'           => array( '.has-$slug-font-family' => 'font-family' ),
 188              'properties'        => array( 'font-family' ),
 189          ),
 190          array(
 191              'path'              => array( 'spacing', 'spacingSizes' ),
 192              'prevent_override'  => array( 'spacing', 'defaultSpacingSizes' ),
 193              'use_default_names' => true,
 194              'value_key'         => 'size',
 195              'css_vars'          => '--wp--preset--spacing--$slug',
 196              'classes'           => array(),
 197              'properties'        => array( 'padding', 'margin' ),
 198          ),
 199          array(
 200              'path'              => array( 'shadow', 'presets' ),
 201              'prevent_override'  => array( 'shadow', 'defaultPresets' ),
 202              'use_default_names' => false,
 203              'value_key'         => 'shadow',
 204              'css_vars'          => '--wp--preset--shadow--$slug',
 205              'classes'           => array(),
 206              'properties'        => array( 'box-shadow' ),
 207          ),
 208      );
 209  
 210      /**
 211       * Metadata for style properties.
 212       *
 213       * Each element is a direct mapping from the CSS property name to the
 214       * path to the value in theme.json & block attributes.
 215       *
 216       * @since 5.8.0
 217       * @since 5.9.0 Added the `border-*`, `font-family`, `font-style`, `font-weight`,
 218       *              `letter-spacing`, `margin-*`, `padding-*`, `--wp--style--block-gap`,
 219       *              `text-decoration`, `text-transform`, and `filter` properties,
 220       *              simplified the metadata structure.
 221       * @since 6.1.0 Added the `border-*-color`, `border-*-width`, `border-*-style`,
 222       *              `--wp--style--root--padding-*`, and `box-shadow` properties,
 223       *              removed the `--wp--style--block-gap` property.
 224       * @since 6.2.0 Added `outline-*`, and `min-height` properties.
 225       * @since 6.3.0 Added `column-count` property.
 226       * @since 6.4.0 Added `writing-mode` property.
 227       * @since 6.5.0 Added `aspect-ratio` property.
 228       * @since 6.6.0 Added `background-[image|position|repeat|size]` properties.
 229       * @since 6.7.0 Added `background-attachment` property.
 230       *
 231       * @var array
 232       */
 233      const PROPERTIES_METADATA = array(
 234          'aspect-ratio'                      => array( 'dimensions', 'aspectRatio' ),
 235          'background'                        => array( 'color', 'gradient' ),
 236          'background-color'                  => array( 'color', 'background' ),
 237          'background-image'                  => array( 'background', 'backgroundImage' ),
 238          'background-position'               => array( 'background', 'backgroundPosition' ),
 239          'background-repeat'                 => array( 'background', 'backgroundRepeat' ),
 240          'background-size'                   => array( 'background', 'backgroundSize' ),
 241          'background-attachment'             => array( 'background', 'backgroundAttachment' ),
 242          'border-radius'                     => array( 'border', 'radius' ),
 243          'border-top-left-radius'            => array( 'border', 'radius', 'topLeft' ),
 244          'border-top-right-radius'           => array( 'border', 'radius', 'topRight' ),
 245          'border-bottom-left-radius'         => array( 'border', 'radius', 'bottomLeft' ),
 246          'border-bottom-right-radius'        => array( 'border', 'radius', 'bottomRight' ),
 247          'border-color'                      => array( 'border', 'color' ),
 248          'border-width'                      => array( 'border', 'width' ),
 249          'border-style'                      => array( 'border', 'style' ),
 250          'border-top-color'                  => array( 'border', 'top', 'color' ),
 251          'border-top-width'                  => array( 'border', 'top', 'width' ),
 252          'border-top-style'                  => array( 'border', 'top', 'style' ),
 253          'border-right-color'                => array( 'border', 'right', 'color' ),
 254          'border-right-width'                => array( 'border', 'right', 'width' ),
 255          'border-right-style'                => array( 'border', 'right', 'style' ),
 256          'border-bottom-color'               => array( 'border', 'bottom', 'color' ),
 257          'border-bottom-width'               => array( 'border', 'bottom', 'width' ),
 258          'border-bottom-style'               => array( 'border', 'bottom', 'style' ),
 259          'border-left-color'                 => array( 'border', 'left', 'color' ),
 260          'border-left-width'                 => array( 'border', 'left', 'width' ),
 261          'border-left-style'                 => array( 'border', 'left', 'style' ),
 262          'color'                             => array( 'color', 'text' ),
 263          'text-align'                        => array( 'typography', 'textAlign' ),
 264          'column-count'                      => array( 'typography', 'textColumns' ),
 265          'font-family'                       => array( 'typography', 'fontFamily' ),
 266          'font-size'                         => array( 'typography', 'fontSize' ),
 267          'font-style'                        => array( 'typography', 'fontStyle' ),
 268          'font-weight'                       => array( 'typography', 'fontWeight' ),
 269          'letter-spacing'                    => array( 'typography', 'letterSpacing' ),
 270          'line-height'                       => array( 'typography', 'lineHeight' ),
 271          'margin'                            => array( 'spacing', 'margin' ),
 272          'margin-top'                        => array( 'spacing', 'margin', 'top' ),
 273          'margin-right'                      => array( 'spacing', 'margin', 'right' ),
 274          'margin-bottom'                     => array( 'spacing', 'margin', 'bottom' ),
 275          'margin-left'                       => array( 'spacing', 'margin', 'left' ),
 276          'min-height'                        => array( 'dimensions', 'minHeight' ),
 277          'outline-color'                     => array( 'outline', 'color' ),
 278          'outline-offset'                    => array( 'outline', 'offset' ),
 279          'outline-style'                     => array( 'outline', 'style' ),
 280          'outline-width'                     => array( 'outline', 'width' ),
 281          'padding'                           => array( 'spacing', 'padding' ),
 282          'padding-top'                       => array( 'spacing', 'padding', 'top' ),
 283          'padding-right'                     => array( 'spacing', 'padding', 'right' ),
 284          'padding-bottom'                    => array( 'spacing', 'padding', 'bottom' ),
 285          'padding-left'                      => array( 'spacing', 'padding', 'left' ),
 286          '--wp--style--root--padding'        => array( 'spacing', 'padding' ),
 287          '--wp--style--root--padding-top'    => array( 'spacing', 'padding', 'top' ),
 288          '--wp--style--root--padding-right'  => array( 'spacing', 'padding', 'right' ),
 289          '--wp--style--root--padding-bottom' => array( 'spacing', 'padding', 'bottom' ),
 290          '--wp--style--root--padding-left'   => array( 'spacing', 'padding', 'left' ),
 291          'text-decoration'                   => array( 'typography', 'textDecoration' ),
 292          'text-transform'                    => array( 'typography', 'textTransform' ),
 293          'filter'                            => array( 'filter', 'duotone' ),
 294          'box-shadow'                        => array( 'shadow' ),
 295          'writing-mode'                      => array( 'typography', 'writingMode' ),
 296      );
 297  
 298      /**
 299       * Indirect metadata for style properties that are not directly output.
 300       *
 301       * Each element maps from a CSS property name to an array of
 302       * paths to the value in theme.json & block attributes.
 303       *
 304       * Indirect properties are not output directly by `compute_style_properties`,
 305       * but are used elsewhere in the processing of global styles. The indirect
 306       * property is used to validate whether a style value is allowed.
 307       *
 308       * @since 6.2.0
 309       * @since 6.6.0 Added background-image properties.
 310       *
 311       * @var array
 312       */
 313      const INDIRECT_PROPERTIES_METADATA = array(
 314          'gap'              => array(
 315              array( 'spacing', 'blockGap' ),
 316          ),
 317          'column-gap'       => array(
 318              array( 'spacing', 'blockGap', 'left' ),
 319          ),
 320          'row-gap'          => array(
 321              array( 'spacing', 'blockGap', 'top' ),
 322          ),
 323          'max-width'        => array(
 324              array( 'layout', 'contentSize' ),
 325              array( 'layout', 'wideSize' ),
 326          ),
 327          'background-image' => array(
 328              array( 'background', 'backgroundImage', 'url' ),
 329          ),
 330      );
 331  
 332      /**
 333       * Protected style properties.
 334       *
 335       * These style properties are only rendered if a setting enables it
 336       * via a value other than `null`.
 337       *
 338       * Each element maps the style property to the corresponding theme.json
 339       * setting key.
 340       *
 341       * @since 5.9.0
 342       */
 343      const PROTECTED_PROPERTIES = array(
 344          'spacing.blockGap' => array( 'spacing', 'blockGap' ),
 345      );
 346  
 347      /**
 348       * The top-level keys a theme.json can have.
 349       *
 350       * @since 5.8.0 As `ALLOWED_TOP_LEVEL_KEYS`.
 351       * @since 5.9.0 Renamed from `ALLOWED_TOP_LEVEL_KEYS` to `VALID_TOP_LEVEL_KEYS`,
 352       *              added the `customTemplates` and `templateParts` values.
 353       * @since 6.3.0 Added the `description` value.
 354       * @since 6.6.0 Added `blockTypes` to support block style variation theme.json partials.
 355       * @var string[]
 356       */
 357      const VALID_TOP_LEVEL_KEYS = array(
 358          'blockTypes',
 359          'customTemplates',
 360          'description',
 361          'patterns',
 362          'settings',
 363          'slug',
 364          'styles',
 365          'templateParts',
 366          'title',
 367          'version',
 368      );
 369  
 370      /**
 371       * The valid properties under the settings key.
 372       *
 373       * @since 5.8.0 As `ALLOWED_SETTINGS`.
 374       * @since 5.9.0 Renamed from `ALLOWED_SETTINGS` to `VALID_SETTINGS`,
 375       *              added new properties for `border`, `color`, `spacing`,
 376       *              and `typography`, and renamed others according to the new schema.
 377       * @since 6.0.0 Added `color.defaultDuotone`.
 378       * @since 6.1.0 Added `layout.definitions` and `useRootPaddingAwareAlignments`.
 379       * @since 6.2.0 Added `dimensions.minHeight`, 'shadow.presets', 'shadow.defaultPresets',
 380       *              `position.fixed` and `position.sticky`.
 381       * @since 6.3.0 Added support for `typography.textColumns`, removed `layout.definitions`.
 382       * @since 6.4.0 Added support for `layout.allowEditing`, `background.backgroundImage`,
 383       *              `typography.writingMode`, `lightbox.enabled` and `lightbox.allowEditing`.
 384       * @since 6.5.0 Added support for `layout.allowCustomContentAndWideSize`,
 385       *              `background.backgroundSize` and `dimensions.aspectRatio`.
 386       * @since 6.6.0 Added support for 'dimensions.aspectRatios', 'dimensions.defaultAspectRatios',
 387       *              'typography.defaultFontSizes', and 'spacing.defaultSpacingSizes'.
 388       * @var array
 389       */
 390      const VALID_SETTINGS = array(
 391          'appearanceTools'               => null,
 392          'useRootPaddingAwareAlignments' => null,
 393          'background'                    => array(
 394              'backgroundImage' => null,
 395              'backgroundSize'  => null,
 396          ),
 397          'border'                        => array(
 398              'color'  => null,
 399              'radius' => null,
 400              'style'  => null,
 401              'width'  => null,
 402          ),
 403          'color'                         => array(
 404              'background'       => null,
 405              'custom'           => null,
 406              'customDuotone'    => null,
 407              'customGradient'   => null,
 408              'defaultDuotone'   => null,
 409              'defaultGradients' => null,
 410              'defaultPalette'   => null,
 411              'duotone'          => null,
 412              'gradients'        => null,
 413              'link'             => null,
 414              'heading'          => null,
 415              'button'           => null,
 416              'caption'          => null,
 417              'palette'          => null,
 418              'text'             => null,
 419          ),
 420          'custom'                        => null,
 421          'dimensions'                    => array(
 422              'aspectRatio'         => null,
 423              'aspectRatios'        => null,
 424              'defaultAspectRatios' => null,
 425              'minHeight'           => null,
 426          ),
 427          'layout'                        => array(
 428              'contentSize'                   => null,
 429              'wideSize'                      => null,
 430              'allowEditing'                  => null,
 431              'allowCustomContentAndWideSize' => null,
 432          ),
 433          'lightbox'                      => array(
 434              'enabled'      => null,
 435              'allowEditing' => null,
 436          ),
 437          'position'                      => array(
 438              'fixed'  => null,
 439              'sticky' => null,
 440          ),
 441          'spacing'                       => array(
 442              'customSpacingSize'   => null,
 443              'defaultSpacingSizes' => null,
 444              'spacingSizes'        => null,
 445              'spacingScale'        => null,
 446              'blockGap'            => null,
 447              'margin'              => null,
 448              'padding'             => null,
 449              'units'               => null,
 450          ),
 451          'shadow'                        => array(
 452              'presets'        => null,
 453              'defaultPresets' => null,
 454          ),
 455          'typography'                    => array(
 456              'fluid'            => null,
 457              'customFontSize'   => null,
 458              'defaultFontSizes' => null,
 459              'dropCap'          => null,
 460              'fontFamilies'     => null,
 461              'fontSizes'        => null,
 462              'fontStyle'        => null,
 463              'fontWeight'       => null,
 464              'letterSpacing'    => null,
 465              'lineHeight'       => null,
 466              'textAlign'        => null,
 467              'textColumns'      => null,
 468              'textDecoration'   => null,
 469              'textTransform'    => null,
 470              'writingMode'      => null,
 471          ),
 472      );
 473  
 474      /*
 475       * The valid properties for fontFamilies under settings key.
 476       *
 477       * @since 6.5.0
 478       *
 479       * @var array
 480       */
 481      const FONT_FAMILY_SCHEMA = array(
 482          array(
 483              'fontFamily' => null,
 484              'name'       => null,
 485              'slug'       => null,
 486              'fontFace'   => array(
 487                  array(
 488                      'ascentOverride'        => null,
 489                      'descentOverride'       => null,
 490                      'fontDisplay'           => null,
 491                      'fontFamily'            => null,
 492                      'fontFeatureSettings'   => null,
 493                      'fontStyle'             => null,
 494                      'fontStretch'           => null,
 495                      'fontVariationSettings' => null,
 496                      'fontWeight'            => null,
 497                      'lineGapOverride'       => null,
 498                      'sizeAdjust'            => null,
 499                      'src'                   => null,
 500                      'unicodeRange'          => null,
 501                  ),
 502              ),
 503          ),
 504      );
 505  
 506      /**
 507       * The valid properties under the styles key.
 508       *
 509       * @since 5.8.0 As `ALLOWED_STYLES`.
 510       * @since 5.9.0 Renamed from `ALLOWED_STYLES` to `VALID_STYLES`,
 511       *              added new properties for `border`, `filter`, `spacing`,
 512       *              and `typography`.
 513       * @since 6.1.0 Added new side properties for `border`,
 514       *              added new property `shadow`,
 515       *              updated `blockGap` to be allowed at any level.
 516       * @since 6.2.0 Added `outline`, and `minHeight` properties.
 517       * @since 6.3.0 Added support for `typography.textColumns`.
 518       * @since 6.5.0 Added support for `dimensions.aspectRatio`.
 519       * @since 6.6.0 Added `background` sub properties to top-level only.
 520       *
 521       * @var array
 522       */
 523      const VALID_STYLES = array(
 524          'background' => array(
 525              'backgroundImage'      => null,
 526              'backgroundPosition'   => null,
 527              'backgroundRepeat'     => null,
 528              'backgroundSize'       => null,
 529              'backgroundAttachment' => null,
 530          ),
 531          'border'     => array(
 532              'color'  => null,
 533              'radius' => null,
 534              'style'  => null,
 535              'width'  => null,
 536              'top'    => null,
 537              'right'  => null,
 538              'bottom' => null,
 539              'left'   => null,
 540          ),
 541          'color'      => array(
 542              'background' => null,
 543              'gradient'   => null,
 544              'text'       => null,
 545          ),
 546          'dimensions' => array(
 547              'aspectRatio' => null,
 548              'minHeight'   => null,
 549          ),
 550          'filter'     => array(
 551              'duotone' => null,
 552          ),
 553          'outline'    => array(
 554              'color'  => null,
 555              'offset' => null,
 556              'style'  => null,
 557              'width'  => null,
 558          ),
 559          'shadow'     => null,
 560          'spacing'    => array(
 561              'margin'   => null,
 562              'padding'  => null,
 563              'blockGap' => null,
 564          ),
 565          'typography' => array(
 566              'fontFamily'     => null,
 567              'fontSize'       => null,
 568              'fontStyle'      => null,
 569              'fontWeight'     => null,
 570              'letterSpacing'  => null,
 571              'lineHeight'     => null,
 572              'textAlign'      => null,
 573              'textColumns'    => null,
 574              'textDecoration' => null,
 575              'textTransform'  => null,
 576              'writingMode'    => null,
 577          ),
 578          'css'        => null,
 579      );
 580  
 581      /**
 582       * Defines which pseudo selectors are enabled for which elements.
 583       *
 584       * The order of the selectors should be: link, any-link, visited, hover, focus, active.
 585       * This is to ensure the user action (hover, focus and active) styles have a higher
 586       * specificity than the visited styles, which in turn have a higher specificity than
 587       * the unvisited styles.
 588       *
 589       * See https://core.trac.wordpress.org/ticket/56928.
 590       * Note: this will affect both top-level and block-level elements.
 591       *
 592       * @since 6.1.0
 593       * @since 6.2.0 Added support for ':link' and ':any-link'.
 594       */
 595      const VALID_ELEMENT_PSEUDO_SELECTORS = array(
 596          'link'   => array( ':link', ':any-link', ':visited', ':hover', ':focus', ':active' ),
 597          'button' => array( ':link', ':any-link', ':visited', ':hover', ':focus', ':active' ),
 598      );
 599  
 600      /**
 601       * The valid elements that can be found under styles.
 602       *
 603       * @since 5.8.0
 604       * @since 6.1.0 Added `heading`, `button`, and `caption` elements.
 605       * @var string[]
 606       */
 607      const ELEMENTS = array(
 608          'link'    => 'a:where(:not(.wp-element-button))', // The `where` is needed to lower the specificity.
 609          'heading' => 'h1, h2, h3, h4, h5, h6',
 610          'h1'      => 'h1',
 611          'h2'      => 'h2',
 612          'h3'      => 'h3',
 613          'h4'      => 'h4',
 614          'h5'      => 'h5',
 615          'h6'      => 'h6',
 616          // We have the .wp-block-button__link class so that this will target older buttons that have been serialized.
 617          'button'  => '.wp-element-button, .wp-block-button__link',
 618          // The block classes are necessary to target older content that won't use the new class names.
 619          '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',
 620          'cite'    => 'cite',
 621      );
 622  
 623      const __EXPERIMENTAL_ELEMENT_CLASS_NAMES = array(
 624          'button'  => 'wp-element-button',
 625          'caption' => 'wp-element-caption',
 626      );
 627  
 628      /**
 629       * List of block support features that can have their related styles
 630       * generated under their own feature level selector rather than the block's.
 631       *
 632       * @since 6.1.0
 633       * @var string[]
 634       */
 635      const BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS = array(
 636          '__experimentalBorder' => 'border',
 637          'color'                => 'color',
 638          'spacing'              => 'spacing',
 639          'typography'           => 'typography',
 640      );
 641  
 642      /**
 643       * Return the input schema at the root and per origin.
 644       *
 645       * @since 6.5.0
 646       *
 647       * @param array $schema The base schema.
 648       * @return array The schema at the root and per origin.
 649       *
 650       * Example:
 651       * schema_in_root_and_per_origin(
 652       *   array(
 653       *    'fontFamily' => null,
 654       *    'slug' => null,
 655       *   )
 656       * )
 657       *
 658       * Returns:
 659       * array(
 660       *  'fontFamily' => null,
 661       *  'slug' => null,
 662       *  'default' => array(
 663       *    'fontFamily' => null,
 664       *    'slug' => null,
 665       *  ),
 666       *  'blocks' => array(
 667       *    'fontFamily' => null,
 668       *    'slug' => null,
 669       *  ),
 670       *  'theme' => array(
 671       *     'fontFamily' => null,
 672       *     'slug' => null,
 673       *  ),
 674       *  'custom' => array(
 675       *     'fontFamily' => null,
 676       *     'slug' => null,
 677       *  ),
 678       * )
 679       */
 680  	protected static function schema_in_root_and_per_origin( $schema ) {
 681          $schema_in_root_and_per_origin = $schema;
 682          foreach ( static::VALID_ORIGINS as $origin ) {
 683              $schema_in_root_and_per_origin[ $origin ] = $schema;
 684          }
 685          return $schema_in_root_and_per_origin;
 686      }
 687  
 688      /**
 689       * Returns a class name by an element name.
 690       *
 691       * @since 6.1.0
 692       *
 693       * @param string $element The name of the element.
 694       * @return string The name of the class.
 695       */
 696  	public static function get_element_class_name( $element ) {
 697          $class_name = '';
 698  
 699          if ( isset( static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $element ] ) ) {
 700              $class_name = static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $element ];
 701          }
 702  
 703          return $class_name;
 704      }
 705  
 706      /**
 707       * Options that settings.appearanceTools enables.
 708       *
 709       * @since 6.0.0
 710       * @since 6.2.0 Added `dimensions.minHeight` and `position.sticky`.
 711       * @since 6.4.0 Added `background.backgroundImage`.
 712       * @since 6.5.0 Added `background.backgroundSize` and `dimensions.aspectRatio`.
 713       * @var array
 714       */
 715      const APPEARANCE_TOOLS_OPT_INS = array(
 716          array( 'background', 'backgroundImage' ),
 717          array( 'background', 'backgroundSize' ),
 718          array( 'border', 'color' ),
 719          array( 'border', 'radius' ),
 720          array( 'border', 'style' ),
 721          array( 'border', 'width' ),
 722          array( 'color', 'link' ),
 723          array( 'color', 'heading' ),
 724          array( 'color', 'button' ),
 725          array( 'color', 'caption' ),
 726          array( 'dimensions', 'aspectRatio' ),
 727          array( 'dimensions', 'minHeight' ),
 728          array( 'position', 'sticky' ),
 729          array( 'spacing', 'blockGap' ),
 730          array( 'spacing', 'margin' ),
 731          array( 'spacing', 'padding' ),
 732          array( 'typography', 'lineHeight' ),
 733      );
 734  
 735      /**
 736       * The latest version of the schema in use.
 737       *
 738       * @since 5.8.0
 739       * @since 5.9.0 Changed value from 1 to 2.
 740       * @since 6.6.0 Changed value from 2 to 3.
 741       * @var int
 742       */
 743      const LATEST_SCHEMA = 3;
 744  
 745      /**
 746       * Constructor.
 747       *
 748       * @since 5.8.0
 749       * @since 6.6.0 Key spacingScale by origin, and Pre-generate the spacingSizes from spacingScale.
 750       *              Added unwrapping of shared block style variations into block type variations if registered.
 751       *
 752       * @param array  $theme_json A structure that follows the theme.json schema.
 753       * @param string $origin     Optional. What source of data this object represents.
 754       *                           One of 'blocks', 'default', 'theme', or 'custom'. Default 'theme'.
 755       */
 756  	public function __construct( $theme_json = array( 'version' => self::LATEST_SCHEMA ), $origin = 'theme' ) {
 757          if ( ! in_array( $origin, static::VALID_ORIGINS, true ) ) {
 758              $origin = 'theme';
 759          }
 760  
 761          $this->theme_json    = WP_Theme_JSON_Schema::migrate( $theme_json, $origin );
 762          $valid_block_names   = array_keys( static::get_blocks_metadata() );
 763          $valid_element_names = array_keys( static::ELEMENTS );
 764          $valid_variations    = static::get_valid_block_style_variations();
 765          $this->theme_json    = static::unwrap_shared_block_style_variations( $this->theme_json, $valid_variations );
 766          $this->theme_json    = static::sanitize( $this->theme_json, $valid_block_names, $valid_element_names, $valid_variations );
 767          $this->theme_json    = static::maybe_opt_in_into_settings( $this->theme_json );
 768  
 769          // Internally, presets are keyed by origin.
 770          $nodes = static::get_setting_nodes( $this->theme_json );
 771          foreach ( $nodes as $node ) {
 772              foreach ( static::PRESETS_METADATA as $preset_metadata ) {
 773                  $path = $node['path'];
 774                  foreach ( $preset_metadata['path'] as $subpath ) {
 775                      $path[] = $subpath;
 776                  }
 777                  $preset = _wp_array_get( $this->theme_json, $path, null );
 778                  if ( null !== $preset ) {
 779                      // If the preset is not already keyed by origin.
 780                      if ( isset( $preset[0] ) || empty( $preset ) ) {
 781                          _wp_array_set( $this->theme_json, $path, array( $origin => $preset ) );
 782                      }
 783                  }
 784              }
 785          }
 786  
 787          // In addition to presets, spacingScale (which generates presets) is also keyed by origin.
 788          $scale_path    = array( 'settings', 'spacing', 'spacingScale' );
 789          $spacing_scale = _wp_array_get( $this->theme_json, $scale_path, null );
 790          if ( null !== $spacing_scale ) {
 791              // If the spacingScale is not already keyed by origin.
 792              if ( empty( array_intersect( array_keys( $spacing_scale ), static::VALID_ORIGINS ) ) ) {
 793                  _wp_array_set( $this->theme_json, $scale_path, array( $origin => $spacing_scale ) );
 794              }
 795          }
 796  
 797          // Pre-generate the spacingSizes from spacingScale.
 798          $scale_path    = array( 'settings', 'spacing', 'spacingScale', $origin );
 799          $spacing_scale = _wp_array_get( $this->theme_json, $scale_path, null );
 800          if ( isset( $spacing_scale ) ) {
 801              $sizes_path           = array( 'settings', 'spacing', 'spacingSizes', $origin );
 802              $spacing_sizes        = _wp_array_get( $this->theme_json, $sizes_path, array() );
 803              $spacing_scale_sizes  = static::compute_spacing_sizes( $spacing_scale );
 804              $merged_spacing_sizes = static::merge_spacing_sizes( $spacing_scale_sizes, $spacing_sizes );
 805              _wp_array_set( $this->theme_json, $sizes_path, $merged_spacing_sizes );
 806          }
 807      }
 808  
 809      /**
 810       * Unwraps shared block style variations.
 811       *
 812       * It takes the shared variations (styles.variations.variationName) and
 813       * applies them to all the blocks that have the given variation registered
 814       * (styles.blocks.blockType.variations.variationName).
 815       *
 816       * For example, given the `core/paragraph` and `core/group` blocks have
 817       * registered the `section-a` style variation, and given the following input:
 818       *
 819       * {
 820       *   "styles": {
 821       *     "variations": {
 822       *       "section-a": { "color": { "background": "backgroundColor" } }
 823       *     }
 824       *   }
 825       * }
 826       *
 827       * It returns the following output:
 828       *
 829       * {
 830       *   "styles": {
 831       *     "blocks": {
 832       *       "core/paragraph": {
 833       *         "variations": {
 834       *             "section-a": { "color": { "background": "backgroundColor" } }
 835       *         },
 836       *       },
 837       *       "core/group": {
 838       *         "variations": {
 839       *           "section-a": { "color": { "background": "backgroundColor" } }
 840       *         }
 841       *       }
 842       *     }
 843       *   }
 844       * }
 845       *
 846       * @since 6.6.0
 847       *
 848       * @param array $theme_json       A structure that follows the theme.json schema.
 849       * @param array $valid_variations Valid block style variations.
 850       * @return array Theme json data with shared variation definitions unwrapped under appropriate block types.
 851       */
 852  	private static function unwrap_shared_block_style_variations( $theme_json, $valid_variations ) {
 853          if ( empty( $theme_json['styles']['variations'] ) || empty( $valid_variations ) ) {
 854              return $theme_json;
 855          }
 856  
 857          $new_theme_json = $theme_json;
 858          $variations     = $new_theme_json['styles']['variations'];
 859  
 860          foreach ( $valid_variations as $block_type => $registered_variations ) {
 861              foreach ( $registered_variations as $variation_name ) {
 862                  $block_level_data = $new_theme_json['styles']['blocks'][ $block_type ]['variations'][ $variation_name ] ?? array();
 863                  $top_level_data   = $variations[ $variation_name ] ?? array();
 864                  $merged_data      = array_replace_recursive( $top_level_data, $block_level_data );
 865                  if ( ! empty( $merged_data ) ) {
 866                      _wp_array_set( $new_theme_json, array( 'styles', 'blocks', $block_type, 'variations', $variation_name ), $merged_data );
 867                  }
 868              }
 869          }
 870  
 871          unset( $new_theme_json['styles']['variations'] );
 872  
 873          return $new_theme_json;
 874      }
 875  
 876      /**
 877       * Enables some opt-in settings if theme declared support.
 878       *
 879       * @since 5.9.0
 880       *
 881       * @param array $theme_json A theme.json structure to modify.
 882       * @return array The modified theme.json structure.
 883       */
 884  	protected static function maybe_opt_in_into_settings( $theme_json ) {
 885          $new_theme_json = $theme_json;
 886  
 887          if (
 888              isset( $new_theme_json['settings']['appearanceTools'] ) &&
 889              true === $new_theme_json['settings']['appearanceTools']
 890          ) {
 891              static::do_opt_in_into_settings( $new_theme_json['settings'] );
 892          }
 893  
 894          if ( isset( $new_theme_json['settings']['blocks'] ) && is_array( $new_theme_json['settings']['blocks'] ) ) {
 895              foreach ( $new_theme_json['settings']['blocks'] as &$block ) {
 896                  if ( isset( $block['appearanceTools'] ) && ( true === $block['appearanceTools'] ) ) {
 897                      static::do_opt_in_into_settings( $block );
 898                  }
 899              }
 900          }
 901  
 902          return $new_theme_json;
 903      }
 904  
 905      /**
 906       * Enables some settings.
 907       *
 908       * @since 5.9.0
 909       *
 910       * @param array $context The context to which the settings belong.
 911       */
 912  	protected static function do_opt_in_into_settings( &$context ) {
 913          foreach ( static::APPEARANCE_TOOLS_OPT_INS as $path ) {
 914              /*
 915               * Use "unset prop" as a marker instead of "null" because
 916               * "null" can be a valid value for some props (e.g. blockGap).
 917               */
 918              if ( 'unset prop' === _wp_array_get( $context, $path, 'unset prop' ) ) {
 919                  _wp_array_set( $context, $path, true );
 920              }
 921          }
 922  
 923          unset( $context['appearanceTools'] );
 924      }
 925  
 926      /**
 927       * Sanitizes the input according to the schemas.
 928       *
 929       * @since 5.8.0
 930       * @since 5.9.0 Added the `$valid_block_names` and `$valid_element_name` parameters.
 931       * @since 6.3.0 Added the `$valid_variations` parameter.
 932       * @since 6.6.0 Updated schema to allow extended block style variations.
 933       *
 934       * @param array $input               Structure to sanitize.
 935       * @param array $valid_block_names   List of valid block names.
 936       * @param array $valid_element_names List of valid element names.
 937       * @param array $valid_variations    List of valid variations per block.
 938       * @return array The sanitized output.
 939       */
 940  	protected static function sanitize( $input, $valid_block_names, $valid_element_names, $valid_variations ) {
 941  
 942          $output = array();
 943  
 944          if ( ! is_array( $input ) ) {
 945              return $output;
 946          }
 947  
 948          // Preserve only the top most level keys.
 949          $output = array_intersect_key( $input, array_flip( static::VALID_TOP_LEVEL_KEYS ) );
 950  
 951          /*
 952           * Remove any rules that are annotated as "top" in VALID_STYLES constant.
 953           * Some styles are only meant to be available at the top-level (e.g.: blockGap),
 954           * hence, the schema for blocks & elements should not have them.
 955           */
 956          $styles_non_top_level = static::VALID_STYLES;
 957          foreach ( array_keys( $styles_non_top_level ) as $section ) {
 958              // array_key_exists() needs to be used instead of isset() because the value can be null.
 959              if ( array_key_exists( $section, $styles_non_top_level ) && is_array( $styles_non_top_level[ $section ] ) ) {
 960                  foreach ( array_keys( $styles_non_top_level[ $section ] ) as $prop ) {
 961                      if ( 'top' === $styles_non_top_level[ $section ][ $prop ] ) {
 962                          unset( $styles_non_top_level[ $section ][ $prop ] );
 963                      }
 964                  }
 965              }
 966          }
 967  
 968          // Build the schema based on valid block & element names.
 969          $schema                 = array();
 970          $schema_styles_elements = array();
 971  
 972          /*
 973           * Set allowed element pseudo selectors based on per element allow list.
 974           * Target data structure in schema:
 975           * e.g.
 976           * - top level elements: `$schema['styles']['elements']['link'][':hover']`.
 977           * - block level elements: `$schema['styles']['blocks']['core/button']['elements']['link'][':hover']`.
 978           */
 979          foreach ( $valid_element_names as $element ) {
 980              $schema_styles_elements[ $element ] = $styles_non_top_level;
 981  
 982              if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) {
 983                  foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
 984                      $schema_styles_elements[ $element ][ $pseudo_selector ] = $styles_non_top_level;
 985                  }
 986              }
 987          }
 988  
 989          $schema_styles_blocks   = array();
 990          $schema_settings_blocks = array();
 991  
 992          /*
 993           * Generate a schema for blocks.
 994           * - Block styles can contain `elements` & `variations` definitions.
 995           * - Variations definitions cannot be nested.
 996           * - Variations can contain styles for inner `blocks`.
 997           * - Variation inner `blocks` styles can contain `elements`.
 998           *
 999           * As each variation needs a `blocks` schema but further nested
1000           * inner `blocks`, the overall schema will be generated in multiple passes.
1001           */
1002          foreach ( $valid_block_names as $block ) {
1003              $schema_settings_blocks[ $block ]           = static::VALID_SETTINGS;
1004              $schema_styles_blocks[ $block ]             = $styles_non_top_level;
1005              $schema_styles_blocks[ $block ]['elements'] = $schema_styles_elements;
1006          }
1007  
1008          $block_style_variation_styles             = static::VALID_STYLES;
1009          $block_style_variation_styles['blocks']   = $schema_styles_blocks;
1010          $block_style_variation_styles['elements'] = $schema_styles_elements;
1011  
1012          foreach ( $valid_block_names as $block ) {
1013              // Build the schema for each block style variation.
1014              $style_variation_names = array();
1015              if (
1016                  ! empty( $input['styles']['blocks'][ $block ]['variations'] ) &&
1017                  is_array( $input['styles']['blocks'][ $block ]['variations'] ) &&
1018                  isset( $valid_variations[ $block ] )
1019              ) {
1020                  $style_variation_names = array_intersect(
1021                      array_keys( $input['styles']['blocks'][ $block ]['variations'] ),
1022                      $valid_variations[ $block ]
1023                  );
1024              }
1025  
1026              $schema_styles_variations = array();
1027              if ( ! empty( $style_variation_names ) ) {
1028                  $schema_styles_variations = array_fill_keys( $style_variation_names, $block_style_variation_styles );
1029              }
1030  
1031              $schema_styles_blocks[ $block ]['variations'] = $schema_styles_variations;
1032          }
1033  
1034          $schema['styles']                                 = static::VALID_STYLES;
1035          $schema['styles']['blocks']                       = $schema_styles_blocks;
1036          $schema['styles']['elements']                     = $schema_styles_elements;
1037          $schema['settings']                               = static::VALID_SETTINGS;
1038          $schema['settings']['blocks']                     = $schema_settings_blocks;
1039          $schema['settings']['typography']['fontFamilies'] = static::schema_in_root_and_per_origin( static::FONT_FAMILY_SCHEMA );
1040  
1041          // Remove anything that's not present in the schema.
1042          foreach ( array( 'styles', 'settings' ) as $subtree ) {
1043              if ( ! isset( $input[ $subtree ] ) ) {
1044                  continue;
1045              }
1046  
1047              if ( ! is_array( $input[ $subtree ] ) ) {
1048                  unset( $output[ $subtree ] );
1049                  continue;
1050              }
1051  
1052              $result = static::remove_keys_not_in_schema( $input[ $subtree ], $schema[ $subtree ] );
1053  
1054              if ( empty( $result ) ) {
1055                  unset( $output[ $subtree ] );
1056              } else {
1057                  $output[ $subtree ] = static::resolve_custom_css_format( $result );
1058              }
1059          }
1060  
1061          return $output;
1062      }
1063  
1064      /**
1065       * Appends a sub-selector to an existing one.
1066       *
1067       * Given the compounded $selector "h1, h2, h3"
1068       * and the $to_append selector ".some-class" the result will be
1069       * "h1.some-class, h2.some-class, h3.some-class".
1070       *
1071       * @since 5.8.0
1072       * @since 6.1.0 Added append position.
1073       * @since 6.3.0 Removed append position parameter.
1074       *
1075       * @param string $selector  Original selector.
1076       * @param string $to_append Selector to append.
1077       * @return string The new selector.
1078       */
1079  	protected static function append_to_selector( $selector, $to_append ) {
1080          if ( ! str_contains( $selector, ',' ) ) {
1081              return $selector . $to_append;
1082          }
1083          $new_selectors = array();
1084          $selectors     = explode( ',', $selector );
1085          foreach ( $selectors as $sel ) {
1086              $new_selectors[] = $sel . $to_append;
1087          }
1088          return implode( ',', $new_selectors );
1089      }
1090  
1091      /**
1092       * Prepends a sub-selector to an existing one.
1093       *
1094       * Given the compounded $selector "h1, h2, h3"
1095       * and the $to_prepend selector ".some-class " the result will be
1096       * ".some-class h1, .some-class  h2, .some-class  h3".
1097       *
1098       * @since 6.3.0
1099       *
1100       * @param string $selector   Original selector.
1101       * @param string $to_prepend Selector to prepend.
1102       * @return string The new selector.
1103       */
1104  	protected static function prepend_to_selector( $selector, $to_prepend ) {
1105          if ( ! str_contains( $selector, ',' ) ) {
1106              return $to_prepend . $selector;
1107          }
1108          $new_selectors = array();
1109          $selectors     = explode( ',', $selector );
1110          foreach ( $selectors as $sel ) {
1111              $new_selectors[] = $to_prepend . $sel;
1112          }
1113          return implode( ',', $new_selectors );
1114      }
1115  
1116      /**
1117       * Returns the metadata for each block.
1118       *
1119       * Example:
1120       *
1121       *     {
1122       *       'core/paragraph': {
1123       *         'selector': 'p',
1124       *         'elements': {
1125       *           'link' => 'link selector',
1126       *           'etc'  => 'element selector'
1127       *         }
1128       *       },
1129       *       'core/heading': {
1130       *         'selector': 'h1',
1131       *         'elements': {}
1132       *       },
1133       *       'core/image': {
1134       *         'selector': '.wp-block-image',
1135       *         'duotone': 'img',
1136       *         'elements': {}
1137       *       }
1138       *     }
1139       *
1140       * @since 5.8.0
1141       * @since 5.9.0 Added `duotone` key with CSS selector.
1142       * @since 6.1.0 Added `features` key with block support feature level selectors.
1143       * @since 6.3.0 Refactored and stabilized selectors API.
1144       * @since 6.6.0 Updated to include block style variations from the block styles registry.
1145       *
1146       * @return array Block metadata.
1147       */
1148  	protected static function get_blocks_metadata() {
1149          $registry       = WP_Block_Type_Registry::get_instance();
1150          $blocks         = $registry->get_all_registered();
1151          $style_registry = WP_Block_Styles_Registry::get_instance();
1152  
1153          // Is there metadata for all currently registered blocks?
1154          $blocks = array_diff_key( $blocks, static::$blocks_metadata );
1155          if ( empty( $blocks ) ) {
1156              /*
1157               * New block styles may have been registered within WP_Block_Styles_Registry.
1158               * Update block metadata for any new block style variations.
1159               */
1160              $registered_styles = $style_registry->get_all_registered();
1161              foreach ( static::$blocks_metadata as $block_name => $block_metadata ) {
1162                  if ( ! empty( $registered_styles[ $block_name ] ) ) {
1163                      $style_selectors = $block_metadata['styleVariations'] ?? array();
1164  
1165                      foreach ( $registered_styles[ $block_name ] as $block_style ) {
1166                          if ( ! isset( $style_selectors[ $block_style['name'] ] ) ) {
1167                              $style_selectors[ $block_style['name'] ] = static::get_block_style_variation_selector( $block_style['name'], $block_metadata['selector'] );
1168                          }
1169                      }
1170  
1171                      static::$blocks_metadata[ $block_name ]['styleVariations'] = $style_selectors;
1172                  }
1173              }
1174              return static::$blocks_metadata;
1175          }
1176  
1177          foreach ( $blocks as $block_name => $block_type ) {
1178              $root_selector = wp_get_block_css_selector( $block_type );
1179  
1180              static::$blocks_metadata[ $block_name ]['selector']  = $root_selector;
1181              static::$blocks_metadata[ $block_name ]['selectors'] = static::get_block_selectors( $block_type, $root_selector );
1182  
1183              $elements = static::get_block_element_selectors( $root_selector );
1184              if ( ! empty( $elements ) ) {
1185                  static::$blocks_metadata[ $block_name ]['elements'] = $elements;
1186              }
1187  
1188              // The block may or may not have a duotone selector.
1189              $duotone_selector = wp_get_block_css_selector( $block_type, 'filter.duotone' );
1190  
1191              // Keep backwards compatibility for support.color.__experimentalDuotone.
1192              if ( null === $duotone_selector ) {
1193                  $duotone_support = isset( $block_type->supports['color']['__experimentalDuotone'] )
1194                      ? $block_type->supports['color']['__experimentalDuotone']
1195                      : null;
1196  
1197                  if ( $duotone_support ) {
1198                      $root_selector    = wp_get_block_css_selector( $block_type );
1199                      $duotone_selector = static::scope_selector( $root_selector, $duotone_support );
1200                  }
1201              }
1202  
1203              if ( null !== $duotone_selector ) {
1204                  static::$blocks_metadata[ $block_name ]['duotone'] = $duotone_selector;
1205              }
1206  
1207              // If the block has style variations, append their selectors to the block metadata.
1208              $style_selectors = array();
1209              if ( ! empty( $block_type->styles ) ) {
1210                  foreach ( $block_type->styles as $style ) {
1211                      $style_selectors[ $style['name'] ] = static::get_block_style_variation_selector( $style['name'], static::$blocks_metadata[ $block_name ]['selector'] );
1212                  }
1213              }
1214  
1215              // Block style variations can be registered through the WP_Block_Styles_Registry as well as block.json.
1216              $registered_styles = $style_registry->get_registered_styles_for_block( $block_name );
1217              foreach ( $registered_styles as $style ) {
1218                  $style_selectors[ $style['name'] ] = static::get_block_style_variation_selector( $style['name'], static::$blocks_metadata[ $block_name ]['selector'] );
1219              }
1220  
1221              if ( ! empty( $style_selectors ) ) {
1222                  static::$blocks_metadata[ $block_name ]['styleVariations'] = $style_selectors;
1223              }
1224          }
1225  
1226          return static::$blocks_metadata;
1227      }
1228  
1229      /**
1230       * Given a tree, removes the keys that are not present in the schema.
1231       *
1232       * It is recursive and modifies the input in-place.
1233       *
1234       * @since 5.8.0
1235       *
1236       * @param array $tree   Input to process.
1237       * @param array $schema Schema to adhere to.
1238       * @return array The modified $tree.
1239       */
1240  	protected static function remove_keys_not_in_schema( $tree, $schema ) {
1241          if ( ! is_array( $tree ) ) {
1242              return $tree;
1243          }
1244  
1245          foreach ( $tree as $key => $value ) {
1246              // Remove keys not in the schema or with null/empty values.
1247              if ( ! array_key_exists( $key, $schema ) ) {
1248                  unset( $tree[ $key ] );
1249                  continue;
1250              }
1251  
1252              if ( is_array( $schema[ $key ] ) ) {
1253                  if ( ! is_array( $value ) ) {
1254                      unset( $tree[ $key ] );
1255                  } elseif ( wp_is_numeric_array( $value ) ) {
1256                      // If indexed, process each item in the array.
1257                      foreach ( $value as $item_key => $item_value ) {
1258                          if ( isset( $schema[ $key ][0] ) && is_array( $schema[ $key ][0] ) ) {
1259                              $tree[ $key ][ $item_key ] = self::remove_keys_not_in_schema( $item_value, $schema[ $key ][0] );
1260                          } else {
1261                              // If the schema does not define a further structure, keep the value as is.
1262                              $tree[ $key ][ $item_key ] = $item_value;
1263                          }
1264                      }
1265                  } else {
1266                      // If associative, process as a single object.
1267                      $tree[ $key ] = self::remove_keys_not_in_schema( $value, $schema[ $key ] );
1268  
1269                      if ( empty( $tree[ $key ] ) ) {
1270                          unset( $tree[ $key ] );
1271                      }
1272                  }
1273              }
1274          }
1275          return $tree;
1276      }
1277  
1278      /**
1279       * Returns the existing settings for each block.
1280       *
1281       * Example:
1282       *
1283       *     {
1284       *       'root': {
1285       *         'color': {
1286       *           'custom': true
1287       *         }
1288       *       },
1289       *       'core/paragraph': {
1290       *         'spacing': {
1291       *           'customPadding': true
1292       *         }
1293       *       }
1294       *     }
1295       *
1296       * @since 5.8.0
1297       *
1298       * @return array Settings per block.
1299       */
1300  	public function get_settings() {
1301          if ( ! isset( $this->theme_json['settings'] ) ) {
1302              return array();
1303          } else {
1304              return $this->theme_json['settings'];
1305          }
1306      }
1307  
1308      /**
1309       * Returns the stylesheet that results of processing
1310       * the theme.json structure this object represents.
1311       *
1312       * @since 5.8.0
1313       * @since 5.9.0 Removed the `$type` parameter, added the `$types` and `$origins` parameters.
1314       * @since 6.3.0 Add fallback layout styles for Post Template when block gap support isn't available.
1315       * @since 6.6.0 Added boolean `skip_root_layout_styles` and `include_block_style_variations` options
1316       *              to control styles output as desired.
1317       *
1318       * @param string[] $types   Types of styles to load. Will load all by default. It accepts:
1319       *                          - `variables`: only the CSS Custom Properties for presets & custom ones.
1320       *                          - `styles`: only the styles section in theme.json.
1321       *                          - `presets`: only the classes for the presets.
1322       * @param string[] $origins A list of origins to include. By default it includes VALID_ORIGINS.
1323       * @param array    $options {
1324       *     Optional. An array of options for now used for internal purposes only (may change without notice).
1325       *
1326       *     @type string $scope                           Makes sure all style are scoped to a given selector
1327       *     @type string $root_selector                   Overwrites and forces a given selector to be used on the root node
1328       *     @type bool   $skip_root_layout_styles         Omits root layout styles from the generated stylesheet. Default false.
1329       *     @type bool   $include_block_style_variations  Includes styles for block style variations in the generated stylesheet. Default false.
1330       * }
1331       * @return string The resulting stylesheet.
1332       */
1333  	public function get_stylesheet( $types = array( 'variables', 'styles', 'presets' ), $origins = null, $options = array() ) {
1334          if ( null === $origins ) {
1335              $origins = static::VALID_ORIGINS;
1336          }
1337  
1338          if ( is_string( $types ) ) {
1339              // Dispatch error and map old arguments to new ones.
1340              _deprecated_argument( __FUNCTION__, '5.9.0' );
1341              if ( 'block_styles' === $types ) {
1342                  $types = array( 'styles', 'presets' );
1343              } elseif ( 'css_variables' === $types ) {
1344                  $types = array( 'variables' );
1345              } else {
1346                  $types = array( 'variables', 'styles', 'presets' );
1347              }
1348          }
1349  
1350          $blocks_metadata = static::get_blocks_metadata();
1351          $style_nodes     = static::get_style_nodes( $this->theme_json, $blocks_metadata, $options );
1352          $setting_nodes   = static::get_setting_nodes( $this->theme_json, $blocks_metadata );
1353  
1354          $root_style_key    = array_search( static::ROOT_BLOCK_SELECTOR, array_column( $style_nodes, 'selector' ), true );
1355          $root_settings_key = array_search( static::ROOT_BLOCK_SELECTOR, array_column( $setting_nodes, 'selector' ), true );
1356  
1357          if ( ! empty( $options['scope'] ) ) {
1358              foreach ( $setting_nodes as &$node ) {
1359                  $node['selector'] = static::scope_selector( $options['scope'], $node['selector'] );
1360              }
1361              foreach ( $style_nodes as &$node ) {
1362                  $node = static::scope_style_node_selectors( $options['scope'], $node );
1363              }
1364              unset( $node );
1365          }
1366  
1367          if ( ! empty( $options['root_selector'] ) ) {
1368              if ( false !== $root_settings_key ) {
1369                  $setting_nodes[ $root_settings_key ]['selector'] = $options['root_selector'];
1370              }
1371              if ( false !== $root_style_key ) {
1372                  $style_nodes[ $root_style_key ]['selector'] = $options['root_selector'];
1373              }
1374          }
1375  
1376          $stylesheet = '';
1377  
1378          if ( in_array( 'variables', $types, true ) ) {
1379              $stylesheet .= $this->get_css_variables( $setting_nodes, $origins );
1380          }
1381  
1382          if ( in_array( 'styles', $types, true ) ) {
1383              if ( false !== $root_style_key && empty( $options['skip_root_layout_styles'] ) ) {
1384                  $stylesheet .= $this->get_root_layout_rules( $style_nodes[ $root_style_key ]['selector'], $style_nodes[ $root_style_key ] );
1385              }
1386              $stylesheet .= $this->get_block_classes( $style_nodes );
1387          } elseif ( in_array( 'base-layout-styles', $types, true ) ) {
1388              $root_selector          = static::ROOT_BLOCK_SELECTOR;
1389              $columns_selector       = '.wp-block-columns';
1390              $post_template_selector = '.wp-block-post-template';
1391              if ( ! empty( $options['scope'] ) ) {
1392                  $root_selector          = static::scope_selector( $options['scope'], $root_selector );
1393                  $columns_selector       = static::scope_selector( $options['scope'], $columns_selector );
1394                  $post_template_selector = static::scope_selector( $options['scope'], $post_template_selector );
1395              }
1396              if ( ! empty( $options['root_selector'] ) ) {
1397                  $root_selector = $options['root_selector'];
1398              }
1399              /*
1400               * Base layout styles are provided as part of `styles`, so only output separately if explicitly requested.
1401               * For backwards compatibility, the Columns block is explicitly included, to support a different default gap value.
1402               */
1403              $base_styles_nodes = array(
1404                  array(
1405                      'path'     => array( 'styles' ),
1406                      'selector' => $root_selector,
1407                  ),
1408                  array(
1409                      'path'     => array( 'styles', 'blocks', 'core/columns' ),
1410                      'selector' => $columns_selector,
1411                      'name'     => 'core/columns',
1412                  ),
1413                  array(
1414                      'path'     => array( 'styles', 'blocks', 'core/post-template' ),
1415                      'selector' => $post_template_selector,
1416                      'name'     => 'core/post-template',
1417                  ),
1418              );
1419  
1420              foreach ( $base_styles_nodes as $base_style_node ) {
1421                  $stylesheet .= $this->get_layout_styles( $base_style_node, $types );
1422              }
1423          }
1424  
1425          if ( in_array( 'presets', $types, true ) ) {
1426              $stylesheet .= $this->get_preset_classes( $setting_nodes, $origins );
1427          }
1428  
1429          // Load the custom CSS last so it has the highest specificity.
1430          if ( in_array( 'custom-css', $types, true ) ) {
1431              // Add the global styles root CSS.
1432              $stylesheet .= _wp_array_get( $this->theme_json, array( 'styles', 'css' ) );
1433          }
1434  
1435          return $stylesheet;
1436      }
1437  
1438      /**
1439       * Processes the CSS, to apply nesting.
1440       *
1441       * @since 6.2.0
1442       * @since 6.6.0 Enforced 0-1-0 specificity for block custom CSS selectors.
1443       *
1444       * @param string $css      The CSS to process.
1445       * @param string $selector The selector to nest.
1446       * @return string The processed CSS.
1447       */
1448  	protected function process_blocks_custom_css( $css, $selector ) {
1449          $processed_css = '';
1450  
1451          if ( empty( $css ) ) {
1452              return $processed_css;
1453          }
1454  
1455          // Split CSS nested rules.
1456          $parts = explode( '&', $css );
1457          foreach ( $parts as $part ) {
1458              if ( empty( $part ) ) {
1459                  continue;
1460              }
1461              $is_root_css = ( ! str_contains( $part, '{' ) );
1462              if ( $is_root_css ) {
1463                  // If the part doesn't contain braces, it applies to the root level.
1464                  $processed_css .= ':root :where(' . trim( $selector ) . '){' . trim( $part ) . '}';
1465              } else {
1466                  // If the part contains braces, it's a nested CSS rule.
1467                  $part = explode( '{', str_replace( '}', '', $part ) );
1468                  if ( count( $part ) !== 2 ) {
1469                      continue;
1470                  }
1471                  $nested_selector = $part[0];
1472                  $css_value       = $part[1];
1473  
1474                  /*
1475                   * Handle pseudo elements such as ::before, ::after etc. Regex will also
1476                   * capture any leading combinator such as >, +, or ~, as well as spaces.
1477                   * This allows pseudo elements as descendants e.g. `.parent ::before`.
1478                   */
1479                  $matches            = array();
1480                  $has_pseudo_element = preg_match( '/([>+~\s]*::[a-zA-Z-]+)/', $nested_selector, $matches );
1481                  $pseudo_part        = $has_pseudo_element ? $matches[1] : '';
1482                  $nested_selector    = $has_pseudo_element ? str_replace( $pseudo_part, '', $nested_selector ) : $nested_selector;
1483  
1484                  // Finalize selector and re-append pseudo element if required.
1485                  $part_selector  = str_starts_with( $nested_selector, ' ' )
1486                      ? static::scope_selector( $selector, $nested_selector )
1487                      : static::append_to_selector( $selector, $nested_selector );
1488                  $final_selector = ":root :where($part_selector)$pseudo_part";
1489  
1490                  $processed_css .= $final_selector . '{' . trim( $css_value ) . '}';
1491              }
1492          }
1493          return $processed_css;
1494      }
1495  
1496      /**
1497       * Returns the global styles custom CSS.
1498       *
1499       * @since 6.2.0
1500       * @deprecated 6.7.0 Use {@see 'get_stylesheet'} instead.
1501       *
1502       * @return string The global styles custom CSS.
1503       */
1504  	public function get_custom_css() {
1505          _deprecated_function( __METHOD__, '6.7.0', 'get_stylesheet' );
1506          // Add the global styles root CSS.
1507          $stylesheet = isset( $this->theme_json['styles']['css'] ) ? $this->theme_json['styles']['css'] : '';
1508  
1509          // Add the global styles block CSS.
1510          if ( isset( $this->theme_json['styles']['blocks'] ) ) {
1511              foreach ( $this->theme_json['styles']['blocks'] as $name => $node ) {
1512                  $custom_block_css = isset( $this->theme_json['styles']['blocks'][ $name ]['css'] )
1513                      ? $this->theme_json['styles']['blocks'][ $name ]['css']
1514                      : null;
1515                  if ( $custom_block_css ) {
1516                      $selector    = static::$blocks_metadata[ $name ]['selector'];
1517                      $stylesheet .= $this->process_blocks_custom_css( $custom_block_css, $selector );
1518                  }
1519              }
1520          }
1521  
1522          return $stylesheet;
1523      }
1524  
1525      /**
1526       * Returns the page templates of the active theme.
1527       *
1528       * @since 5.9.0
1529       *
1530       * @return array
1531       */
1532  	public function get_custom_templates() {
1533          $custom_templates = array();
1534          if ( ! isset( $this->theme_json['customTemplates'] ) || ! is_array( $this->theme_json['customTemplates'] ) ) {
1535              return $custom_templates;
1536          }
1537  
1538          foreach ( $this->theme_json['customTemplates'] as $item ) {
1539              if ( isset( $item['name'] ) ) {
1540                  $custom_templates[ $item['name'] ] = array(
1541                      'title'     => isset( $item['title'] ) ? $item['title'] : '',
1542                      'postTypes' => isset( $item['postTypes'] ) ? $item['postTypes'] : array( 'page' ),
1543                  );
1544              }
1545          }
1546          return $custom_templates;
1547      }
1548  
1549      /**
1550       * Returns the template part data of active theme.
1551       *
1552       * @since 5.9.0
1553       *
1554       * @return array
1555       */
1556  	public function get_template_parts() {
1557          $template_parts = array();
1558          if ( ! isset( $this->theme_json['templateParts'] ) || ! is_array( $this->theme_json['templateParts'] ) ) {
1559              return $template_parts;
1560          }
1561  
1562          foreach ( $this->theme_json['templateParts'] as $item ) {
1563              if ( isset( $item['name'] ) ) {
1564                  $template_parts[ $item['name'] ] = array(
1565                      'title' => isset( $item['title'] ) ? $item['title'] : '',
1566                      'area'  => isset( $item['area'] ) ? $item['area'] : '',
1567                  );
1568              }
1569          }
1570          return $template_parts;
1571      }
1572  
1573      /**
1574       * Converts each style section into a list of rulesets
1575       * containing the block styles to be appended to the stylesheet.
1576       *
1577       * See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax
1578       *
1579       * For each section this creates a new ruleset such as:
1580       *
1581       *   block-selector {
1582       *     style-property-one: value;
1583       *   }
1584       *
1585       * @since 5.8.0 As `get_block_styles()`.
1586       * @since 5.9.0 Renamed from `get_block_styles()` to `get_block_classes()`
1587       *              and no longer returns preset classes.
1588       *              Removed the `$setting_nodes` parameter.
1589       * @since 6.1.0 Moved most internal logic to `get_styles_for_block()`.
1590       *
1591       * @param array $style_nodes Nodes with styles.
1592       * @return string The new stylesheet.
1593       */
1594  	protected function get_block_classes( $style_nodes ) {
1595          $block_rules = '';
1596  
1597          foreach ( $style_nodes as $metadata ) {
1598              if ( null === $metadata['selector'] ) {
1599                  continue;
1600              }
1601              $block_rules .= static::get_styles_for_block( $metadata );
1602          }
1603  
1604          return $block_rules;
1605      }
1606  
1607      /**
1608       * Gets the CSS layout rules for a particular block from theme.json layout definitions.
1609       *
1610       * @since 6.1.0
1611       * @since 6.3.0 Reduced specificity for layout margin rules.
1612       * @since 6.5.1 Only output rules referencing content and wide sizes when values exist.
1613       * @since 6.5.3 Add types parameter to check if only base layout styles are needed.
1614       * @since 6.6.0 Updated layout style specificity to be compatible with overall 0-1-0 specificity in global styles.
1615       *
1616       * @param array $block_metadata Metadata about the block to get styles for.
1617       * @param array $types          Optional. Types of styles to output. If empty, all styles will be output.
1618       * @return string Layout styles for the block.
1619       */
1620  	protected function get_layout_styles( $block_metadata, $types = array() ) {
1621          $block_rules = '';
1622          $block_type  = null;
1623  
1624          // Skip outputting layout styles if explicitly disabled.
1625          if ( current_theme_supports( 'disable-layout-styles' ) ) {
1626              return $block_rules;
1627          }
1628  
1629          if ( isset( $block_metadata['name'] ) ) {
1630              $block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block_metadata['name'] );
1631              if ( ! block_has_support( $block_type, 'layout', false ) && ! block_has_support( $block_type, '__experimentalLayout', false ) ) {
1632                  return $block_rules;
1633              }
1634          }
1635  
1636          $selector                 = isset( $block_metadata['selector'] ) ? $block_metadata['selector'] : '';
1637          $has_block_gap_support    = isset( $this->theme_json['settings']['spacing']['blockGap'] );
1638          $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.
1639          $node                     = _wp_array_get( $this->theme_json, $block_metadata['path'], array() );
1640          $layout_definitions       = wp_get_layout_definitions();
1641          $layout_selector_pattern  = '/^[a-zA-Z0-9\-\.\,\ *+>:\(\)]*$/'; // Allow alphanumeric classnames, spaces, wildcard, sibling, child combinator and pseudo class selectors.
1642  
1643          /*
1644           * Gap styles will only be output if the theme has block gap support, or supports a fallback gap.
1645           * Default layout gap styles will be skipped for themes that do not explicitly opt-in to blockGap with a `true` or `false` value.
1646           */
1647          if ( $has_block_gap_support || $has_fallback_gap_support ) {
1648              $block_gap_value = null;
1649              // Use a fallback gap value if block gap support is not available.
1650              if ( ! $has_block_gap_support ) {
1651                  $block_gap_value = static::ROOT_BLOCK_SELECTOR === $selector ? '0.5em' : null;
1652                  if ( ! empty( $block_type ) ) {
1653                      $block_gap_value = isset( $block_type->supports['spacing']['blockGap']['__experimentalDefault'] )
1654                          ? $block_type->supports['spacing']['blockGap']['__experimentalDefault']
1655                          : null;
1656                  }
1657              } else {
1658                  $block_gap_value = static::get_property_value( $node, array( 'spacing', 'blockGap' ) );
1659              }
1660  
1661              // Support split row / column values and concatenate to a shorthand value.
1662              if ( is_array( $block_gap_value ) ) {
1663                  if ( isset( $block_gap_value['top'] ) && isset( $block_gap_value['left'] ) ) {
1664                      $gap_row         = static::get_property_value( $node, array( 'spacing', 'blockGap', 'top' ) );
1665                      $gap_column      = static::get_property_value( $node, array( 'spacing', 'blockGap', 'left' ) );
1666                      $block_gap_value = $gap_row === $gap_column ? $gap_row : $gap_row . ' ' . $gap_column;
1667                  } else {
1668                      // Skip outputting gap value if not all sides are provided.
1669                      $block_gap_value = null;
1670                  }
1671              }
1672  
1673              // If the block should have custom gap, add the gap styles.
1674              if ( null !== $block_gap_value && false !== $block_gap_value && '' !== $block_gap_value ) {
1675                  foreach ( $layout_definitions as $layout_definition_key => $layout_definition ) {
1676                      // Allow outputting fallback gap styles for flex and grid layout types when block gap support isn't available.
1677                      if ( ! $has_block_gap_support && 'flex' !== $layout_definition_key && 'grid' !== $layout_definition_key ) {
1678                          continue;
1679                      }
1680  
1681                      $class_name    = isset( $layout_definition['className'] ) ? $layout_definition['className'] : false;
1682                      $spacing_rules = isset( $layout_definition['spacingStyles'] ) ? $layout_definition['spacingStyles'] : array();
1683  
1684                      if (
1685                          ! empty( $class_name ) &&
1686                          ! empty( $spacing_rules )
1687                      ) {
1688                          foreach ( $spacing_rules as $spacing_rule ) {
1689                              $declarations = array();
1690                              if (
1691                                  isset( $spacing_rule['selector'] ) &&
1692                                  preg_match( $layout_selector_pattern, $spacing_rule['selector'] ) &&
1693                                  ! empty( $spacing_rule['rules'] )
1694                              ) {
1695                                  // Iterate over each of the styling rules and substitute non-string values such as `null` with the real `blockGap` value.
1696                                  foreach ( $spacing_rule['rules'] as $css_property => $css_value ) {
1697                                      $current_css_value = is_string( $css_value ) ? $css_value : $block_gap_value;
1698                                      if ( static::is_safe_css_declaration( $css_property, $current_css_value ) ) {
1699                                          $declarations[] = array(
1700                                              'name'  => $css_property,
1701                                              'value' => $current_css_value,
1702                                          );
1703                                      }
1704                                  }
1705  
1706                                  if ( ! $has_block_gap_support ) {
1707                                      // For fallback gap styles, use lower specificity, to ensure styles do not unintentionally override theme styles.
1708                                      $format          = static::ROOT_BLOCK_SELECTOR === $selector ? ':where(.%2$s%3$s)' : ':where(%1$s.%2$s%3$s)';
1709                                      $layout_selector = sprintf(
1710                                          $format,
1711                                          $selector,
1712                                          $class_name,
1713                                          $spacing_rule['selector']
1714                                      );
1715                                  } else {
1716                                      $format          = static::ROOT_BLOCK_SELECTOR === $selector ? ':root :where(.%2$s)%3$s' : ':root :where(%1$s-%2$s)%3$s';
1717                                      $layout_selector = sprintf(
1718                                          $format,
1719                                          $selector,
1720                                          $class_name,
1721                                          $spacing_rule['selector']
1722                                      );
1723                                  }
1724                                  $block_rules .= static::to_ruleset( $layout_selector, $declarations );
1725                              }
1726                          }
1727                      }
1728                  }
1729              }
1730          }
1731  
1732          // Output base styles.
1733          if (
1734              static::ROOT_BLOCK_SELECTOR === $selector
1735          ) {
1736              $valid_display_modes = array( 'block', 'flex', 'grid' );
1737              foreach ( $layout_definitions as $layout_definition ) {
1738                  $class_name       = isset( $layout_definition['className'] ) ? $layout_definition['className'] : false;
1739                  $base_style_rules = isset( $layout_definition['baseStyles'] ) ? $layout_definition['baseStyles'] : array();
1740  
1741                  if (
1742                      ! empty( $class_name ) &&
1743                      is_array( $base_style_rules )
1744                  ) {
1745                      // Output display mode. This requires special handling as `display` is not exposed in `safe_style_css_filter`.
1746                      if (
1747                          ! empty( $layout_definition['displayMode'] ) &&
1748                          is_string( $layout_definition['displayMode'] ) &&
1749                          in_array( $layout_definition['displayMode'], $valid_display_modes, true )
1750                      ) {
1751                          $layout_selector = sprintf(
1752                              '%s .%s',
1753                              $selector,
1754                              $class_name
1755                          );
1756                          $block_rules    .= static::to_ruleset(
1757                              $layout_selector,
1758                              array(
1759                                  array(
1760                                      'name'  => 'display',
1761                                      'value' => $layout_definition['displayMode'],
1762                                  ),
1763                              )
1764                          );
1765                      }
1766  
1767                      foreach ( $base_style_rules as $base_style_rule ) {
1768                          $declarations = array();
1769  
1770                          // Skip outputting base styles for flow and constrained layout types if theme doesn't support theme.json. The 'base-layout-styles' type flags this.
1771                          if ( in_array( 'base-layout-styles', $types, true ) && ( 'default' === $layout_definition['name'] || 'constrained' === $layout_definition['name'] ) ) {
1772                              continue;
1773                          }
1774  
1775                          if (
1776                              isset( $base_style_rule['selector'] ) &&
1777                              preg_match( $layout_selector_pattern, $base_style_rule['selector'] ) &&
1778                              ! empty( $base_style_rule['rules'] )
1779                          ) {
1780                              foreach ( $base_style_rule['rules'] as $css_property => $css_value ) {
1781                                  // Skip rules that reference content size or wide size if they are not defined in the theme.json.
1782                                  if (
1783                                      is_string( $css_value ) &&
1784                                      ( str_contains( $css_value, '--global--content-size' ) || str_contains( $css_value, '--global--wide-size' ) ) &&
1785                                      ! isset( $this->theme_json['settings']['layout']['contentSize'] ) &&
1786                                      ! isset( $this->theme_json['settings']['layout']['wideSize'] )
1787                                  ) {
1788                                      continue;
1789                                  }
1790  
1791                                  if ( static::is_safe_css_declaration( $css_property, $css_value ) ) {
1792                                      $declarations[] = array(
1793                                          'name'  => $css_property,
1794                                          'value' => $css_value,
1795                                      );
1796                                  }
1797                              }
1798  
1799                              $layout_selector = sprintf(
1800                                  '.%s%s',
1801                                  $class_name,
1802                                  $base_style_rule['selector']
1803                              );
1804                              $block_rules    .= static::to_ruleset( $layout_selector, $declarations );
1805                          }
1806                      }
1807                  }
1808              }
1809          }
1810          return $block_rules;
1811      }
1812  
1813      /**
1814       * Creates new rulesets as classes for each preset value such as:
1815       *
1816       *   .has-value-color {
1817       *     color: value;
1818       *   }
1819       *
1820       *   .has-value-background-color {
1821       *     background-color: value;
1822       *   }
1823       *
1824       *   .has-value-font-size {
1825       *     font-size: value;
1826       *   }
1827       *
1828       *   .has-value-gradient-background {
1829       *     background: value;
1830       *   }
1831       *
1832       *   p.has-value-gradient-background {
1833       *     background: value;
1834       *   }
1835       *
1836       * @since 5.9.0
1837       *
1838       * @param array    $setting_nodes Nodes with settings.
1839       * @param string[] $origins       List of origins to process presets from.
1840       * @return string The new stylesheet.
1841       */
1842  	protected function get_preset_classes( $setting_nodes, $origins ) {
1843          $preset_rules = '';
1844  
1845          foreach ( $setting_nodes as $metadata ) {
1846              if ( null === $metadata['selector'] ) {
1847                  continue;
1848              }
1849  
1850              $selector      = $metadata['selector'];
1851              $node          = _wp_array_get( $this->theme_json, $metadata['path'], array() );
1852              $preset_rules .= static::compute_preset_classes( $node, $selector, $origins );
1853          }
1854  
1855          return $preset_rules;
1856      }
1857  
1858      /**
1859       * Converts each styles section into a list of rulesets
1860       * to be appended to the stylesheet.
1861       * These rulesets contain all the css variables (custom variables and preset variables).
1862       *
1863       * See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax
1864       *
1865       * For each section this creates a new ruleset such as:
1866       *
1867       *     block-selector {
1868       *       --wp--preset--category--slug: value;
1869       *       --wp--custom--variable: value;
1870       *     }
1871       *
1872       * @since 5.8.0
1873       * @since 5.9.0 Added the `$origins` parameter.
1874       *
1875       * @param array    $nodes   Nodes with settings.
1876       * @param string[] $origins List of origins to process.
1877       * @return string The new stylesheet.
1878       */
1879  	protected function get_css_variables( $nodes, $origins ) {
1880          $stylesheet = '';
1881          foreach ( $nodes as $metadata ) {
1882              if ( null === $metadata['selector'] ) {
1883                  continue;
1884              }
1885  
1886              $selector = $metadata['selector'];
1887  
1888              $node                    = _wp_array_get( $this->theme_json, $metadata['path'], array() );
1889              $declarations            = static::compute_preset_vars( $node, $origins );
1890              $theme_vars_declarations = static::compute_theme_vars( $node );
1891              foreach ( $theme_vars_declarations as $theme_vars_declaration ) {
1892                  $declarations[] = $theme_vars_declaration;
1893              }
1894  
1895              $stylesheet .= static::to_ruleset( $selector, $declarations );
1896          }
1897  
1898          return $stylesheet;
1899      }
1900  
1901      /**
1902       * Given a selector and a declaration list,
1903       * creates the corresponding ruleset.
1904       *
1905       * @since 5.8.0
1906       *
1907       * @param string $selector     CSS selector.
1908       * @param array  $declarations List of declarations.
1909       * @return string The resulting CSS ruleset.
1910       */
1911  	protected static function to_ruleset( $selector, $declarations ) {
1912          if ( empty( $declarations ) ) {
1913              return '';
1914          }
1915  
1916          $declaration_block = array_reduce(
1917              $declarations,
1918              static function ( $carry, $element ) {
1919                  return $carry .= $element['name'] . ': ' . $element['value'] . ';'; },
1920              ''
1921          );
1922  
1923          return $selector . '{' . $declaration_block . '}';
1924      }
1925  
1926      /**
1927       * Given a settings array, returns the generated rulesets
1928       * for the preset classes.
1929       *
1930       * @since 5.8.0
1931       * @since 5.9.0 Added the `$origins` parameter.
1932       * @since 6.6.0 Added check for root CSS properties selector.
1933       *
1934       * @param array    $settings Settings to process.
1935       * @param string   $selector Selector wrapping the classes.
1936       * @param string[] $origins  List of origins to process.
1937       * @return string The result of processing the presets.
1938       */
1939  	protected static function compute_preset_classes( $settings, $selector, $origins ) {
1940          if ( static::ROOT_BLOCK_SELECTOR === $selector || static::ROOT_CSS_PROPERTIES_SELECTOR === $selector ) {
1941              /*
1942               * Classes at the global level do not need any CSS prefixed,
1943               * and we don't want to increase its specificity.
1944               */
1945              $selector = '';
1946          }
1947  
1948          $stylesheet = '';
1949          foreach ( static::PRESETS_METADATA as $preset_metadata ) {
1950              if ( empty( $preset_metadata['classes'] ) ) {
1951                  continue;
1952              }
1953              $slugs = static::get_settings_slugs( $settings, $preset_metadata, $origins );
1954              foreach ( $preset_metadata['classes'] as $class => $property ) {
1955                  foreach ( $slugs as $slug ) {
1956                      $css_var    = static::replace_slug_in_string( $preset_metadata['css_vars'], $slug );
1957                      $class_name = static::replace_slug_in_string( $class, $slug );
1958  
1959                      // $selector is often empty, so we can save ourselves the `append_to_selector()` call then.
1960                      $new_selector = '' === $selector ? $class_name : static::append_to_selector( $selector, $class_name );
1961                      $stylesheet  .= static::to_ruleset(
1962                          $new_selector,
1963                          array(
1964                              array(
1965                                  'name'  => $property,
1966                                  'value' => 'var(' . $css_var . ') !important',
1967                              ),
1968                          )
1969                      );
1970                  }
1971              }
1972          }
1973  
1974          return $stylesheet;
1975      }
1976  
1977      /**
1978       * Function that scopes a selector with another one. This works a bit like
1979       * SCSS nesting except the `&` operator isn't supported.
1980       *
1981       * <code>
1982       * $scope = '.a, .b .c';
1983       * $selector = '> .x, .y';
1984       * $merged = scope_selector( $scope, $selector );
1985       * // $merged is '.a > .x, .a .y, .b .c > .x, .b .c .y'
1986       * </code>
1987       *
1988       * @since 5.9.0
1989       * @since 6.6.0 Added early return if missing scope or selector.
1990       *
1991       * @param string $scope    Selector to scope to.
1992       * @param string $selector Original selector.
1993       * @return string Scoped selector.
1994       */
1995  	public static function scope_selector( $scope, $selector ) {
1996          if ( ! $scope || ! $selector ) {
1997              return $selector;
1998          }
1999  
2000          $scopes    = explode( ',', $scope );
2001          $selectors = explode( ',', $selector );
2002  
2003          $selectors_scoped = array();
2004          foreach ( $scopes as $outer ) {
2005              foreach ( $selectors as $inner ) {
2006                  $outer = trim( $outer );
2007                  $inner = trim( $inner );
2008                  if ( ! empty( $outer ) && ! empty( $inner ) ) {
2009                      $selectors_scoped[] = $outer . ' ' . $inner;
2010                  } elseif ( empty( $outer ) ) {
2011                      $selectors_scoped[] = $inner;
2012                  } elseif ( empty( $inner ) ) {
2013                      $selectors_scoped[] = $outer;
2014                  }
2015              }
2016          }
2017  
2018          $result = implode( ', ', $selectors_scoped );
2019          return $result;
2020      }
2021  
2022      /**
2023       * Scopes the selectors for a given style node.
2024       *
2025       * This includes the primary selector, i.e. `$node['selector']`, as well as any custom
2026       * selectors for features and subfeatures, e.g. `$node['selectors']['border']` etc.
2027       *
2028       * @since 6.6.0
2029       *
2030       * @param string $scope Selector to scope to.
2031       * @param array  $node  Style node with selectors to scope.
2032       * @return array Node with updated selectors.
2033       */
2034  	protected static function scope_style_node_selectors( $scope, $node ) {
2035          $node['selector'] = static::scope_selector( $scope, $node['selector'] );
2036  
2037          if ( empty( $node['selectors'] ) ) {
2038              return $node;
2039          }
2040  
2041          foreach ( $node['selectors'] as $feature => $selector ) {
2042              if ( is_string( $selector ) ) {
2043                  $node['selectors'][ $feature ] = static::scope_selector( $scope, $selector );
2044              }
2045              if ( is_array( $selector ) ) {
2046                  foreach ( $selector as $subfeature => $subfeature_selector ) {
2047                      $node['selectors'][ $feature ][ $subfeature ] = static::scope_selector( $scope, $subfeature_selector );
2048                  }
2049              }
2050          }
2051  
2052          return $node;
2053      }
2054  
2055      /**
2056       * Gets preset values keyed by slugs based on settings and metadata.
2057       *
2058       * <code>
2059       * $settings = array(
2060       *     'typography' => array(
2061       *         'fontFamilies' => array(
2062       *             array(
2063       *                 'slug'       => 'sansSerif',
2064       *                 'fontFamily' => '"Helvetica Neue", sans-serif',
2065       *             ),
2066       *             array(
2067       *                 'slug'   => 'serif',
2068       *                 'colors' => 'Georgia, serif',
2069       *             )
2070       *         ),
2071       *     ),
2072       * );
2073       * $meta = array(
2074       *    'path'      => array( 'typography', 'fontFamilies' ),
2075       *    'value_key' => 'fontFamily',
2076       * );
2077       * $values_by_slug = get_settings_values_by_slug();
2078       * // $values_by_slug === array(
2079       * //   'sans-serif' => '"Helvetica Neue", sans-serif',
2080       * //   'serif'      => 'Georgia, serif',
2081       * // );
2082       * </code>
2083       *
2084       * @since 5.9.0
2085       * @since 6.6.0 Passing $settings to the callbacks defined in static::PRESETS_METADATA.
2086       *
2087       * @param array    $settings        Settings to process.
2088       * @param array    $preset_metadata One of the PRESETS_METADATA values.
2089       * @param string[] $origins         List of origins to process.
2090       * @return array Array of presets where each key is a slug and each value is the preset value.
2091       */
2092  	protected static function get_settings_values_by_slug( $settings, $preset_metadata, $origins ) {
2093          $preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() );
2094  
2095          $result = array();
2096          foreach ( $origins as $origin ) {
2097              if ( ! isset( $preset_per_origin[ $origin ] ) ) {
2098                  continue;
2099              }
2100              foreach ( $preset_per_origin[ $origin ] as $preset ) {
2101                  $slug = _wp_to_kebab_case( $preset['slug'] );
2102  
2103                  $value = '';
2104                  if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) {
2105                      $value_key = $preset_metadata['value_key'];
2106                      $value     = $preset[ $value_key ];
2107                  } elseif (
2108                      isset( $preset_metadata['value_func'] ) &&
2109                      is_callable( $preset_metadata['value_func'] )
2110                  ) {
2111                      $value_func = $preset_metadata['value_func'];
2112                      $value      = call_user_func( $value_func, $preset, $settings );
2113                  } else {
2114                      // If we don't have a value, then don't add it to the result.
2115                      continue;
2116                  }
2117  
2118                  $result[ $slug ] = $value;
2119              }
2120          }
2121          return $result;
2122      }
2123  
2124      /**
2125       * Similar to get_settings_values_by_slug, but doesn't compute the value.
2126       *
2127       * @since 5.9.0
2128       *
2129       * @param array    $settings        Settings to process.
2130       * @param array    $preset_metadata One of the PRESETS_METADATA values.
2131       * @param string[] $origins         List of origins to process.
2132       * @return array Array of presets where the key and value are both the slug.
2133       */
2134  	protected static function get_settings_slugs( $settings, $preset_metadata, $origins = null ) {
2135          if ( null === $origins ) {
2136              $origins = static::VALID_ORIGINS;
2137          }
2138  
2139          $preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() );
2140  
2141          $result = array();
2142          foreach ( $origins as $origin ) {
2143              if ( ! isset( $preset_per_origin[ $origin ] ) ) {
2144                  continue;
2145              }
2146              foreach ( $preset_per_origin[ $origin ] as $preset ) {
2147                  $slug = _wp_to_kebab_case( $preset['slug'] );
2148  
2149                  // Use the array as a set so we don't get duplicates.
2150                  $result[ $slug ] = $slug;
2151              }
2152          }
2153          return $result;
2154      }
2155  
2156      /**
2157       * Transforms a slug into a CSS Custom Property.
2158       *
2159       * @since 5.9.0
2160       *
2161       * @param string $input String to replace.
2162       * @param string $slug  The slug value to use to generate the custom property.
2163       * @return string The CSS Custom Property. Something along the lines of `--wp--preset--color--black`.
2164       */
2165  	protected static function replace_slug_in_string( $input, $slug ) {
2166          return strtr( $input, array( '$slug' => $slug ) );
2167      }
2168  
2169      /**
2170       * Given the block settings, extracts the CSS Custom Properties
2171       * for the presets and adds them to the $declarations array
2172       * following the format:
2173       *
2174       *     array(
2175       *       'name'  => 'property_name',
2176       *       'value' => 'property_value,
2177       *     )
2178       *
2179       * @since 5.8.0
2180       * @since 5.9.0 Added the `$origins` parameter.
2181       *
2182       * @param array    $settings Settings to process.
2183       * @param string[] $origins  List of origins to process.
2184       * @return array The modified $declarations.
2185       */
2186  	protected static function compute_preset_vars( $settings, $origins ) {
2187          $declarations = array();
2188          foreach ( static::PRESETS_METADATA as $preset_metadata ) {
2189              if ( empty( $preset_metadata['css_vars'] ) ) {
2190                  continue;
2191              }
2192              $values_by_slug = static::get_settings_values_by_slug( $settings, $preset_metadata, $origins );
2193              foreach ( $values_by_slug as $slug => $value ) {
2194                  $declarations[] = array(
2195                      'name'  => static::replace_slug_in_string( $preset_metadata['css_vars'], $slug ),
2196                      'value' => $value,
2197                  );
2198              }
2199          }
2200  
2201          return $declarations;
2202      }
2203  
2204      /**
2205       * Given an array of settings, extracts the CSS Custom Properties
2206       * for the custom values and adds them to the $declarations
2207       * array following the format:
2208       *
2209       *     array(
2210       *       'name'  => 'property_name',
2211       *       'value' => 'property_value,
2212       *     )
2213       *
2214       * @since 5.8.0
2215       *
2216       * @param array $settings Settings to process.
2217       * @return array The modified $declarations.
2218       */
2219  	protected static function compute_theme_vars( $settings ) {
2220          $declarations  = array();
2221          $custom_values = isset( $settings['custom'] ) ? $settings['custom'] : array();
2222          $css_vars      = static::flatten_tree( $custom_values );
2223          foreach ( $css_vars as $key => $value ) {
2224              $declarations[] = array(
2225                  'name'  => '--wp--custom--' . $key,
2226                  'value' => $value,
2227              );
2228          }
2229  
2230          return $declarations;
2231      }
2232  
2233      /**
2234       * Given a tree, it creates a flattened one
2235       * by merging the keys and binding the leaf values
2236       * to the new keys.
2237       *
2238       * It also transforms camelCase names into kebab-case
2239       * and substitutes '/' by '-'.
2240       *
2241       * This is thought to be useful to generate
2242       * CSS Custom Properties from a tree,
2243       * although there's nothing in the implementation
2244       * of this function that requires that format.
2245       *
2246       * For example, assuming the given prefix is '--wp'
2247       * and the token is '--', for this input tree:
2248       *
2249       *     {
2250       *       'some/property': 'value',
2251       *       'nestedProperty': {
2252       *         'sub-property': 'value'
2253       *       }
2254       *     }
2255       *
2256       * it'll return this output:
2257       *
2258       *     {
2259       *       '--wp--some-property': 'value',
2260       *       '--wp--nested-property--sub-property': 'value'
2261       *     }
2262       *
2263       * @since 5.8.0
2264       *
2265       * @param array  $tree   Input tree to process.
2266       * @param string $prefix Optional. Prefix to prepend to each variable. Default empty string.
2267       * @param string $token  Optional. Token to use between levels. Default '--'.
2268       * @return array The flattened tree.
2269       */
2270  	protected static function flatten_tree( $tree, $prefix = '', $token = '--' ) {
2271          $result = array();
2272          foreach ( $tree as $property => $value ) {
2273              $new_key = $prefix . str_replace(
2274                  '/',
2275                  '-',
2276                  strtolower( _wp_to_kebab_case( $property ) )
2277              );
2278  
2279              if ( is_array( $value ) ) {
2280                  $new_prefix        = $new_key . $token;
2281                  $flattened_subtree = static::flatten_tree( $value, $new_prefix, $token );
2282                  foreach ( $flattened_subtree as $subtree_key => $subtree_value ) {
2283                      $result[ $subtree_key ] = $subtree_value;
2284                  }
2285              } else {
2286                  $result[ $new_key ] = $value;
2287              }
2288          }
2289          return $result;
2290      }
2291  
2292      /**
2293       * Given a styles array, it extracts the style properties
2294       * and adds them to the $declarations array following the format:
2295       *
2296       *     array(
2297       *       'name'  => 'property_name',
2298       *       'value' => 'property_value',
2299       *     )
2300       *
2301       * @since 5.8.0
2302       * @since 5.9.0 Added the `$settings` and `$properties` parameters.
2303       * @since 6.1.0 Added `$theme_json`, `$selector`, and `$use_root_padding` parameters.
2304       * @since 6.5.0 Output a `min-height: unset` rule when `aspect-ratio` is set.
2305       * @since 6.6.0 Pass current theme JSON settings to wp_get_typography_font_size_value(), and process background properties.
2306       * @since 6.7.0 `ref` resolution of background properties, and assigning custom default values.
2307       *
2308       * @param array   $styles Styles to process.
2309       * @param array   $settings Theme settings.
2310       * @param array   $properties Properties metadata.
2311       * @param array   $theme_json Theme JSON array.
2312       * @param string  $selector The style block selector.
2313       * @param boolean $use_root_padding Whether to add custom properties at root level.
2314       * @return array  Returns the modified $declarations.
2315       */
2316  	protected static function compute_style_properties( $styles, $settings = array(), $properties = null, $theme_json = null, $selector = null, $use_root_padding = null ) {
2317          if ( null === $properties ) {
2318              $properties = static::PROPERTIES_METADATA;
2319          }
2320  
2321          $declarations = array();
2322          if ( empty( $styles ) ) {
2323              return $declarations;
2324          }
2325  
2326          $root_variable_duplicates = array();
2327  
2328          foreach ( $properties as $css_property => $value_path ) {
2329              $value = static::get_property_value( $styles, $value_path, $theme_json );
2330  
2331              if ( str_starts_with( $css_property, '--wp--style--root--' ) && ( static::ROOT_BLOCK_SELECTOR !== $selector || ! $use_root_padding ) ) {
2332                  continue;
2333              }
2334              /*
2335               * Root-level padding styles don't currently support strings with CSS shorthand values.
2336               * This may change: https://github.com/WordPress/gutenberg/issues/40132.
2337               */
2338              if ( '--wp--style--root--padding' === $css_property && is_string( $value ) ) {
2339                  continue;
2340              }
2341  
2342              if ( str_starts_with( $css_property, '--wp--style--root--' ) && $use_root_padding ) {
2343                  $root_variable_duplicates[] = substr( $css_property, strlen( '--wp--style--root--' ) );
2344              }
2345  
2346              /*
2347               * Look up protected properties, keyed by value path.
2348               * Skip protected properties that are explicitly set to `null`.
2349               */
2350              if ( is_array( $value_path ) ) {
2351                  $path_string = implode( '.', $value_path );
2352                  if (
2353                      isset( static::PROTECTED_PROPERTIES[ $path_string ] ) &&
2354                      _wp_array_get( $settings, static::PROTECTED_PROPERTIES[ $path_string ], null ) === null
2355                  ) {
2356                      continue;
2357                  }
2358              }
2359  
2360              /*
2361               * Processes background image styles.
2362               * If the value is a URL, it will be converted to a CSS `url()` value.
2363               * For uploaded image (images with a database ID), apply size and position defaults,
2364               * equal to those applied in block supports in lib/background.php.
2365               */
2366              if ( 'background-image' === $css_property && ! empty( $value ) ) {
2367                  $background_styles = wp_style_engine_get_styles(
2368                      array( 'background' => array( 'backgroundImage' => $value ) )
2369                  );
2370                  $value             = $background_styles['declarations'][ $css_property ];
2371              }
2372              if ( empty( $value ) && static::ROOT_BLOCK_SELECTOR !== $selector && ! empty( $styles['background']['backgroundImage']['id'] ) ) {
2373                  if ( 'background-size' === $css_property ) {
2374                      $value = 'cover';
2375                  }
2376                  // If the background size is set to `contain` and no position is set, set the position to `center`.
2377                  if ( 'background-position' === $css_property ) {
2378                      $background_size = $styles['background']['backgroundSize'] ?? null;
2379                      $value           = 'contain' === $background_size ? '50% 50%' : null;
2380                  }
2381              }
2382  
2383              // Skip if empty and not "0" or value represents array of longhand values.
2384              $has_missing_value = empty( $value ) && ! is_numeric( $value );
2385              if ( $has_missing_value || is_array( $value ) ) {
2386                  continue;
2387              }
2388  
2389              // Calculates fluid typography rules where available.
2390              if ( 'font-size' === $css_property ) {
2391                  /*
2392                   * wp_get_typography_font_size_value() will check
2393                   * if fluid typography has been activated and also
2394                   * whether the incoming value can be converted to a fluid value.
2395                   * Values that already have a clamp() function will not pass the test,
2396                   * and therefore the original $value will be returned.
2397                   * Pass the current theme_json settings to override any global settings.
2398                   */
2399                  $value = wp_get_typography_font_size_value( array( 'size' => $value ), $settings );
2400              }
2401  
2402              if ( 'aspect-ratio' === $css_property ) {
2403                  // For aspect ratio to work, other dimensions rules must be unset.
2404                  // This ensures that a fixed height does not override the aspect ratio.
2405                  $declarations[] = array(
2406                      'name'  => 'min-height',
2407                      'value' => 'unset',
2408                  );
2409              }
2410  
2411              $declarations[] = array(
2412                  'name'  => $css_property,
2413                  'value' => $value,
2414              );
2415          }
2416  
2417          // If a variable value is added to the root, the corresponding property should be removed.
2418          foreach ( $root_variable_duplicates as $duplicate ) {
2419              $discard = array_search( $duplicate, array_column( $declarations, 'name' ), true );
2420              if ( is_numeric( $discard ) ) {
2421                  array_splice( $declarations, $discard, 1 );
2422              }
2423          }
2424  
2425          return $declarations;
2426      }
2427  
2428      /**
2429       * Returns the style property for the given path.
2430       *
2431       * It also converts references to a path to the value
2432       * stored at that location, e.g.
2433       * { "ref": "style.color.background" } => "#fff".
2434       *
2435       * @since 5.8.0
2436       * @since 5.9.0 Added support for values of array type, which are returned as is.
2437       * @since 6.1.0 Added the `$theme_json` parameter.
2438       * @since 6.3.0 It no longer converts the internal format "var:preset|color|secondary"
2439       *              to the standard form "--wp--preset--color--secondary".
2440       *              This is already done by the sanitize method,
2441       *              so every property will be in the standard form.
2442       * @since 6.7.0 Added support for background image refs.
2443       *
2444       * @param array $styles Styles subtree.
2445       * @param array $path   Which property to process.
2446       * @param array $theme_json Theme JSON array.
2447       * @return string|array Style property value.
2448       */
2449  	protected static function get_property_value( $styles, $path, $theme_json = null ) {
2450          $value = _wp_array_get( $styles, $path, '' );
2451  
2452          if ( '' === $value || null === $value ) {
2453              // No need to process the value further.
2454              return '';
2455          }
2456  
2457          /*
2458           * This converts references to a path to the value at that path
2459           * where the value is an array with a "ref" key, pointing to a path.
2460           * For example: { "ref": "style.color.background" } => "#fff".
2461           * In the case of backgroundImage, if both a ref and a URL are present in the value,
2462           * the URL takes precedence and the ref is ignored.
2463           */
2464          if ( is_array( $value ) && isset( $value['ref'] ) ) {
2465              $value_path = explode( '.', $value['ref'] );
2466              $ref_value  = _wp_array_get( $theme_json, $value_path );
2467              // Background Image refs can refer to a string or an array containing a URL string.
2468              $ref_value_url = $ref_value['url'] ?? null;
2469              // Only use the ref value if we find anything.
2470              if ( ! empty( $ref_value ) && ( is_string( $ref_value ) || is_string( $ref_value_url ) ) ) {
2471                  $value = $ref_value;
2472              }
2473  
2474              if ( is_array( $ref_value ) && isset( $ref_value['ref'] ) ) {
2475                  $path_string      = json_encode( $path );
2476                  $ref_value_string = json_encode( $ref_value );
2477                  _doing_it_wrong(
2478                      'get_property_value',
2479                      sprintf(
2480                          /* translators: 1: theme.json, 2: Value name, 3: Value path, 4: Another value name. */
2481                          __( '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.' ),
2482                          'theme.json',
2483                          $ref_value_string,
2484                          $path_string,
2485                          $ref_value['ref']
2486                      ),
2487                      '6.1.0'
2488                  );
2489              }
2490          }
2491  
2492          if ( is_array( $value ) ) {
2493              return $value;
2494          }
2495  
2496          return $value;
2497      }
2498  
2499      /**
2500       * Builds metadata for the setting nodes, which returns in the form of:
2501       *
2502       *     [
2503       *       [
2504       *         'path'     => ['path', 'to', 'some', 'node' ],
2505       *         'selector' => 'CSS selector for some node'
2506       *       ],
2507       *       [
2508       *         'path'     => [ 'path', 'to', 'other', 'node' ],
2509       *         'selector' => 'CSS selector for other node'
2510       *       ],
2511       *     ]
2512       *
2513       * @since 5.8.0
2514       *
2515       * @param array $theme_json The tree to extract setting nodes from.
2516       * @param array $selectors  List of selectors per block.
2517       * @return array An array of setting nodes metadata.
2518       */
2519  	protected static function get_setting_nodes( $theme_json, $selectors = array() ) {
2520          $nodes = array();
2521          if ( ! isset( $theme_json['settings'] ) ) {
2522              return $nodes;
2523          }
2524  
2525          // Top-level.
2526          $nodes[] = array(
2527              'path'     => array( 'settings' ),
2528              'selector' => static::ROOT_CSS_PROPERTIES_SELECTOR,
2529          );
2530  
2531          // Calculate paths for blocks.
2532          if ( ! isset( $theme_json['settings']['blocks'] ) ) {
2533              return $nodes;
2534          }
2535  
2536          foreach ( $theme_json['settings']['blocks'] as $name => $node ) {
2537              $selector = null;
2538              if ( isset( $selectors[ $name ]['selector'] ) ) {
2539                  $selector = $selectors[ $name ]['selector'];
2540              }
2541  
2542              $nodes[] = array(
2543                  'path'     => array( 'settings', 'blocks', $name ),
2544                  'selector' => $selector,
2545              );
2546          }
2547  
2548          return $nodes;
2549      }
2550  
2551      /**
2552       * Builds metadata for the style nodes, which returns in the form of:
2553       *
2554       *     [
2555       *       [
2556       *         'path'     => [ 'path', 'to', 'some', 'node' ],
2557       *         'selector' => 'CSS selector for some node',
2558       *         'duotone'  => 'CSS selector for duotone for some node'
2559       *       ],
2560       *       [
2561       *         'path'     => ['path', 'to', 'other', 'node' ],
2562       *         'selector' => 'CSS selector for other node',
2563       *         'duotone'  => null
2564       *       ],
2565       *     ]
2566       *
2567       * @since 5.8.0
2568       * @since 6.6.0 Added options array for modifying generated nodes.
2569       *
2570       * @param array $theme_json The tree to extract style nodes from.
2571       * @param array $selectors  List of selectors per block.
2572       * @param array $options {
2573       *     Optional. An array of options for now used for internal purposes only (may change without notice).
2574       *
2575       *     @type bool $include_block_style_variations Includes style nodes for block style variations. Default false.
2576       * }
2577       * @return array An array of style nodes metadata.
2578       */
2579  	protected static function get_style_nodes( $theme_json, $selectors = array(), $options = array() ) {
2580          $nodes = array();
2581          if ( ! isset( $theme_json['styles'] ) ) {
2582              return $nodes;
2583          }
2584  
2585          // Top-level.
2586          $nodes[] = array(
2587              'path'     => array( 'styles' ),
2588              'selector' => static::ROOT_BLOCK_SELECTOR,
2589          );
2590  
2591          if ( isset( $theme_json['styles']['elements'] ) ) {
2592              foreach ( self::ELEMENTS as $element => $selector ) {
2593                  if ( ! isset( $theme_json['styles']['elements'][ $element ] ) ) {
2594                      continue;
2595                  }
2596                  $nodes[] = array(
2597                      'path'     => array( 'styles', 'elements', $element ),
2598                      'selector' => static::ELEMENTS[ $element ],
2599                  );
2600  
2601                  // Handle any pseudo selectors for the element.
2602                  if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) {
2603                      foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
2604  
2605                          if ( isset( $theme_json['styles']['elements'][ $element ][ $pseudo_selector ] ) ) {
2606                              $nodes[] = array(
2607                                  'path'     => array( 'styles', 'elements', $element ),
2608                                  'selector' => static::append_to_selector( static::ELEMENTS[ $element ], $pseudo_selector ),
2609                              );
2610                          }
2611                      }
2612                  }
2613              }
2614          }
2615  
2616          // Blocks.
2617          if ( ! isset( $theme_json['styles']['blocks'] ) ) {
2618              return $nodes;
2619          }
2620  
2621          $block_nodes = static::get_block_nodes( $theme_json, $selectors, $options );
2622          foreach ( $block_nodes as $block_node ) {
2623              $nodes[] = $block_node;
2624          }
2625  
2626          /**
2627           * Filters the list of style nodes with metadata.
2628           *
2629           * This allows for things like loading block CSS independently.
2630           *
2631           * @since 6.1.0
2632           *
2633           * @param array $nodes Style nodes with metadata.
2634           */
2635          return apply_filters( 'wp_theme_json_get_style_nodes', $nodes );
2636      }
2637  
2638      /**
2639       * A public helper to get the block nodes from a theme.json file.
2640       *
2641       * @since 6.1.0
2642       *
2643       * @return array The block nodes in theme.json.
2644       */
2645  	public function get_styles_block_nodes() {
2646          return static::get_block_nodes( $this->theme_json );
2647      }
2648  
2649      /**
2650       * Returns a filtered declarations array if there is a separator block with only a background
2651       * style defined in theme.json by adding a color attribute to reflect the changes in the front.
2652       *
2653       * @since 6.1.1
2654       *
2655       * @param array $declarations List of declarations.
2656       * @return array $declarations List of declarations filtered.
2657       */
2658  	private static function update_separator_declarations( $declarations ) {
2659          $background_color     = '';
2660          $border_color_matches = false;
2661          $text_color_matches   = false;
2662  
2663          foreach ( $declarations as $declaration ) {
2664              if ( 'background-color' === $declaration['name'] && ! $background_color && isset( $declaration['value'] ) ) {
2665                  $background_color = $declaration['value'];
2666              } elseif ( 'border-color' === $declaration['name'] ) {
2667                  $border_color_matches = true;
2668              } elseif ( 'color' === $declaration['name'] ) {
2669                  $text_color_matches = true;
2670              }
2671  
2672              if ( $background_color && $border_color_matches && $text_color_matches ) {
2673                  break;
2674              }
2675          }
2676  
2677          if ( $background_color && ! $border_color_matches && ! $text_color_matches ) {
2678              $declarations[] = array(
2679                  'name'  => 'color',
2680                  'value' => $background_color,
2681              );
2682          }
2683  
2684          return $declarations;
2685      }
2686  
2687      /**
2688       * An internal method to get the block nodes from a theme.json file.
2689       *
2690       * @since 6.1.0
2691       * @since 6.3.0 Refactored and stabilized selectors API.
2692       * @since 6.6.0 Added optional selectors and options for generating block nodes.
2693       *
2694       * @param array $theme_json The theme.json converted to an array.
2695       * @param array $selectors  Optional list of selectors per block.
2696       * @param array $options {
2697       *     Optional. An array of options for now used for internal purposes only (may change without notice).
2698       *
2699       *     @type bool   $include_block_style_variations  Includes nodes for block style variations. Default false.
2700       * }
2701       * @return array The block nodes in theme.json.
2702       */
2703  	private static function get_block_nodes( $theme_json, $selectors = array(), $options = array() ) {
2704          $selectors = empty( $selectors ) ? static::get_blocks_metadata() : $selectors;
2705          $nodes     = array();
2706          if ( ! isset( $theme_json['styles'] ) ) {
2707              return $nodes;
2708          }
2709  
2710          // Blocks.
2711          if ( ! isset( $theme_json['styles']['blocks'] ) ) {
2712              return $nodes;
2713          }
2714  
2715          foreach ( $theme_json['styles']['blocks'] as $name => $node ) {
2716              $selector = null;
2717              if ( isset( $selectors[ $name ]['selector'] ) ) {
2718                  $selector = $selectors[ $name ]['selector'];
2719              }
2720  
2721              $duotone_selector = null;
2722              if ( isset( $selectors[ $name ]['duotone'] ) ) {
2723                  $duotone_selector = $selectors[ $name ]['duotone'];
2724              }
2725  
2726              $feature_selectors = null;
2727              if ( isset( $selectors[ $name ]['selectors'] ) ) {
2728                  $feature_selectors = $selectors[ $name ]['selectors'];
2729              }
2730  
2731              $variation_selectors = array();
2732              $include_variations  = $options['include_block_style_variations'] ?? false;
2733              if ( $include_variations && isset( $node['variations'] ) ) {
2734                  foreach ( $node['variations'] as $variation => $node ) {
2735                      $variation_selectors[] = array(
2736                          'path'     => array( 'styles', 'blocks', $name, 'variations', $variation ),
2737                          'selector' => $selectors[ $name ]['styleVariations'][ $variation ],
2738                      );
2739                  }
2740              }
2741  
2742              $nodes[] = array(
2743                  'name'       => $name,
2744                  'path'       => array( 'styles', 'blocks', $name ),
2745                  'selector'   => $selector,
2746                  'selectors'  => $feature_selectors,
2747                  'duotone'    => $duotone_selector,
2748                  'features'   => $feature_selectors,
2749                  'variations' => $variation_selectors,
2750                  'css'        => $selector,
2751              );
2752  
2753              if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'] ) ) {
2754                  foreach ( $theme_json['styles']['blocks'][ $name ]['elements'] as $element => $node ) {
2755                      $nodes[] = array(
2756                          'path'     => array( 'styles', 'blocks', $name, 'elements', $element ),
2757                          'selector' => $selectors[ $name ]['elements'][ $element ],
2758                      );
2759  
2760                      // Handle any pseudo selectors for the element.
2761                      if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] ) ) {
2762                          foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
2763                              if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'][ $element ][ $pseudo_selector ] ) ) {
2764                                  $nodes[] = array(
2765                                      'path'     => array( 'styles', 'blocks', $name, 'elements', $element ),
2766                                      'selector' => static::append_to_selector( $selectors[ $name ]['elements'][ $element ], $pseudo_selector ),
2767                                  );
2768                              }
2769                          }
2770                      }
2771                  }
2772              }
2773          }
2774  
2775          return $nodes;
2776      }
2777  
2778      /**
2779       * Gets the CSS rules for a particular block from theme.json.
2780       *
2781       * @since 6.1.0
2782       * @since 6.6.0 Setting a min-height of HTML when root styles have a background gradient or image.
2783       *              Updated general global styles specificity to 0-1-0.
2784       *              Fixed custom CSS output in block style variations.
2785       *
2786       * @param array $block_metadata Metadata about the block to get styles for.
2787       *
2788       * @return string Styles for the block.
2789       */
2790  	public function get_styles_for_block( $block_metadata ) {
2791          $node                 = _wp_array_get( $this->theme_json, $block_metadata['path'], array() );
2792          $use_root_padding     = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments'];
2793          $selector             = $block_metadata['selector'];
2794          $settings             = isset( $this->theme_json['settings'] ) ? $this->theme_json['settings'] : array();
2795          $feature_declarations = static::get_feature_declarations_for_node( $block_metadata, $node );
2796          $is_root_selector     = static::ROOT_BLOCK_SELECTOR === $selector;
2797  
2798          // If there are style variations, generate the declarations for them, including any feature selectors the block may have.
2799          $style_variation_declarations = array();
2800          $style_variation_custom_css   = array();
2801          if ( ! empty( $block_metadata['variations'] ) ) {
2802              foreach ( $block_metadata['variations'] as $style_variation ) {
2803                  $style_variation_node           = _wp_array_get( $this->theme_json, $style_variation['path'], array() );
2804                  $clean_style_variation_selector = trim( $style_variation['selector'] );
2805  
2806                  // Generate any feature/subfeature style declarations for the current style variation.
2807                  $variation_declarations = static::get_feature_declarations_for_node( $block_metadata, $style_variation_node );
2808  
2809                  // Combine selectors with style variation's selector and add to overall style variation declarations.
2810                  foreach ( $variation_declarations as $current_selector => $new_declarations ) {
2811                      // If current selector includes block classname, remove it but leave the whitespace in.
2812                      $shortened_selector = str_replace( $block_metadata['selector'] . ' ', ' ', $current_selector );
2813  
2814                      // Prepend the variation selector to the current selector.
2815                      $split_selectors    = explode( ',', $shortened_selector );
2816                      $updated_selectors  = array_map(
2817                          static function ( $split_selector ) use ( $clean_style_variation_selector ) {
2818                              return $clean_style_variation_selector . $split_selector;
2819                          },
2820                          $split_selectors
2821                      );
2822                      $combined_selectors = implode( ',', $updated_selectors );
2823  
2824                      // Add the new declarations to the overall results under the modified selector.
2825                      $style_variation_declarations[ $combined_selectors ] = $new_declarations;
2826                  }
2827  
2828                  // Compute declarations for remaining styles not covered by feature level selectors.
2829                  $style_variation_declarations[ $style_variation['selector'] ] = static::compute_style_properties( $style_variation_node, $settings, null, $this->theme_json );
2830                  // Store custom CSS for the style variation.
2831                  if ( isset( $style_variation_node['css'] ) ) {
2832                      $style_variation_custom_css[ $style_variation['selector'] ] = $this->process_blocks_custom_css( $style_variation_node['css'], $style_variation['selector'] );
2833                  }
2834              }
2835          }
2836          /*
2837           * Get a reference to element name from path.
2838           * $block_metadata['path'] = array( 'styles','elements','link' );
2839           * Make sure that $block_metadata['path'] describes an element node, like [ 'styles', 'element', 'link' ].
2840           * Skip non-element paths like just ['styles'].
2841           */
2842          $is_processing_element = in_array( 'elements', $block_metadata['path'], true );
2843  
2844          $current_element = $is_processing_element ? $block_metadata['path'][ count( $block_metadata['path'] ) - 1 ] : null;
2845  
2846          $element_pseudo_allowed = array();
2847  
2848          if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) ) {
2849              $element_pseudo_allowed = static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ];
2850          }
2851  
2852          /*
2853           * Check for allowed pseudo classes (e.g. ":hover") from the $selector ("a:hover").
2854           * This also resets the array keys.
2855           */
2856          $pseudo_matches = array_values(
2857              array_filter(
2858                  $element_pseudo_allowed,
2859                  static function ( $pseudo_selector ) use ( $selector ) {
2860                      return str_contains( $selector, $pseudo_selector );
2861                  }
2862              )
2863          );
2864  
2865          $pseudo_selector = isset( $pseudo_matches[0] ) ? $pseudo_matches[0] : null;
2866  
2867          /*
2868           * If the current selector is a pseudo selector that's defined in the allow list for the current
2869           * element then compute the style properties for it.
2870           * Otherwise just compute the styles for the default selector as normal.
2871           */
2872          if ( $pseudo_selector && isset( $node[ $pseudo_selector ] ) &&
2873              isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] )
2874              && in_array( $pseudo_selector, static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ], true )
2875          ) {
2876              $declarations = static::compute_style_properties( $node[ $pseudo_selector ], $settings, null, $this->theme_json, $selector, $use_root_padding );
2877          } else {
2878              $declarations = static::compute_style_properties( $node, $settings, null, $this->theme_json, $selector, $use_root_padding );
2879          }
2880  
2881          $block_rules = '';
2882  
2883          /*
2884           * 1. Bespoke declaration modifiers:
2885           * - 'filter': Separate the declarations that use the general selector
2886           * from the ones using the duotone selector.
2887           * - 'background|background-image': set the html min-height to 100%
2888           * to ensure the background covers the entire viewport.
2889           */
2890          $declarations_duotone       = array();
2891          $should_set_root_min_height = false;
2892  
2893          foreach ( $declarations as $index => $declaration ) {
2894              if ( 'filter' === $declaration['name'] ) {
2895                  /*
2896                   * 'unset' filters happen when a filter is unset
2897                   * in the site-editor UI. Because the 'unset' value
2898                   * in the user origin overrides the value in the
2899                   * theme origin, we can skip rendering anything
2900                   * here as no filter needs to be applied anymore.
2901                   * So only add declarations to with values other
2902                   * than 'unset'.
2903                   */
2904                  if ( 'unset' !== $declaration['value'] ) {
2905                      $declarations_duotone[] = $declaration;
2906                  }
2907                  unset( $declarations[ $index ] );
2908              }
2909  
2910              if ( $is_root_selector && ( 'background-image' === $declaration['name'] || 'background' === $declaration['name'] ) ) {
2911                  $should_set_root_min_height = true;
2912              }
2913          }
2914  
2915          /*
2916           * If root styles has a background-image or a background (gradient) set,
2917           * set the min-height to '100%'. Minus `--wp-admin--admin-bar--height` for logged-in view.
2918           * Setting the CSS rule on the HTML tag ensures background gradients and images behave similarly,
2919           * and matches the behavior of the site editor.
2920           */
2921          if ( $should_set_root_min_height ) {
2922              $block_rules .= static::to_ruleset(
2923                  'html',
2924                  array(
2925                      array(
2926                          'name'  => 'min-height',
2927                          'value' => 'calc(100% - var(--wp-admin--admin-bar--height, 0px))',
2928                      ),
2929                  )
2930              );
2931          }
2932  
2933          // Update declarations if there are separators with only background color defined.
2934          if ( '.wp-block-separator' === $selector ) {
2935              $declarations = static::update_separator_declarations( $declarations );
2936          }
2937  
2938          /*
2939           * Root selector (body) styles should not be wrapped in `:root where()` to keep
2940           * specificity at (0,0,1) and maintain backwards compatibility.
2941           *
2942           * Top-level element styles using element-only specificity selectors should
2943           * not get wrapped in `:root :where()` to maintain backwards compatibility.
2944           *
2945           * Pseudo classes, e.g. :hover, :focus etc., are a class-level selector so
2946           * still need to be wrapped in `:root :where` to cap specificity for nested
2947           * variations etc. Pseudo selectors won't match the ELEMENTS selector exactly.
2948           */
2949          $element_only_selector = $is_root_selector || (
2950              $current_element &&
2951              isset( static::ELEMENTS[ $current_element ] ) &&
2952              // buttons, captions etc. still need `:root :where()` as they are class based selectors.
2953              ! isset( static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $current_element ] ) &&
2954              static::ELEMENTS[ $current_element ] === $selector
2955          );
2956  
2957          // 2. Generate and append the rules that use the general selector.
2958          $general_selector = $element_only_selector ? $selector : ":root :where($selector)";
2959          $block_rules     .= static::to_ruleset( $general_selector, $declarations );
2960  
2961          // 3. Generate and append the rules that use the duotone selector.
2962          if ( isset( $block_metadata['duotone'] ) && ! empty( $declarations_duotone ) ) {
2963              $block_rules .= static::to_ruleset( $block_metadata['duotone'], $declarations_duotone );
2964          }
2965  
2966          // 4. Generate Layout block gap styles.
2967          if (
2968              ! $is_root_selector &&
2969              ! empty( $block_metadata['name'] )
2970          ) {
2971              $block_rules .= $this->get_layout_styles( $block_metadata );
2972          }
2973  
2974          // 5. Generate and append the feature level rulesets.
2975          foreach ( $feature_declarations as $feature_selector => $individual_feature_declarations ) {
2976              $block_rules .= static::to_ruleset( ":root :where($feature_selector)", $individual_feature_declarations );
2977          }
2978  
2979          // 6. Generate and append the style variation rulesets.
2980          foreach ( $style_variation_declarations as $style_variation_selector => $individual_style_variation_declarations ) {
2981              $block_rules .= static::to_ruleset( ":root :where($style_variation_selector)", $individual_style_variation_declarations );
2982              if ( isset( $style_variation_custom_css[ $style_variation_selector ] ) ) {
2983                  $block_rules .= $style_variation_custom_css[ $style_variation_selector ];
2984              }
2985          }
2986  
2987          // 7. Generate and append any custom CSS rules.
2988          if ( isset( $node['css'] ) && ! $is_root_selector ) {
2989              $block_rules .= $this->process_blocks_custom_css( $node['css'], $selector );
2990          }
2991  
2992          return $block_rules;
2993      }
2994  
2995      /**
2996       * Outputs the CSS for layout rules on the root.
2997       *
2998       * @since 6.1.0
2999       * @since 6.6.0 Use `ROOT_CSS_PROPERTIES_SELECTOR` for CSS custom properties and improved consistency of root padding rules.
3000       *              Updated specificity of body margin reset and first/last child selectors.
3001       *
3002       * @param string $selector The root node selector.
3003       * @param array  $block_metadata The metadata for the root block.
3004       * @return string The additional root rules CSS.
3005       */
3006  	public function get_root_layout_rules( $selector, $block_metadata ) {
3007          $css              = '';
3008          $settings         = isset( $this->theme_json['settings'] ) ? $this->theme_json['settings'] : array();
3009          $use_root_padding = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments'];
3010  
3011          /*
3012          * If there are content and wide widths in theme.json, output them
3013          * as custom properties on the body element so all blocks can use them.
3014          */
3015          if ( isset( $settings['layout']['contentSize'] ) || isset( $settings['layout']['wideSize'] ) ) {
3016              $content_size = isset( $settings['layout']['contentSize'] ) ? $settings['layout']['contentSize'] : $settings['layout']['wideSize'];
3017              $content_size = static::is_safe_css_declaration( 'max-width', $content_size ) ? $content_size : 'initial';
3018              $wide_size    = isset( $settings['layout']['wideSize'] ) ? $settings['layout']['wideSize'] : $settings['layout']['contentSize'];
3019              $wide_size    = static::is_safe_css_declaration( 'max-width', $wide_size ) ? $wide_size : 'initial';
3020              $css         .= static::ROOT_CSS_PROPERTIES_SELECTOR . ' { --wp--style--global--content-size: ' . $content_size . ';';
3021              $css         .= '--wp--style--global--wide-size: ' . $wide_size . '; }';
3022          }
3023  
3024          /*
3025          * Reset default browser margin on the body element.
3026          * This is set on the body selector **before** generating the ruleset
3027          * from the `theme.json`. This is to ensure that if the `theme.json` declares
3028          * `margin` in its `spacing` declaration for the `body` element then these
3029          * user-generated values take precedence in the CSS cascade.
3030          * @link https://github.com/WordPress/gutenberg/issues/36147.
3031          */
3032          $css .= ':where(body) { margin: 0; }';
3033  
3034          if ( $use_root_padding ) {
3035              // Top and bottom padding are applied to the outer block container.
3036              $css .= '.wp-site-blocks { padding-top: var(--wp--style--root--padding-top); padding-bottom: var(--wp--style--root--padding-bottom); }';
3037              // Right and left padding are applied to the first container with `.has-global-padding` class.
3038              $css .= '.has-global-padding { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }';
3039              // Alignfull children of the container with left and right padding have negative margins so they can still be full width.
3040              $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); }';
3041              // 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.
3042              $css .= '.has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull)) { padding-right: 0; padding-left: 0; }';
3043              // Alignfull direct children of the containers that are targeted by the rule above do not need negative margins.
3044              $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; }';
3045          }
3046  
3047          $css .= '.wp-site-blocks > .alignleft { float: left; margin-right: 2em; }';
3048          $css .= '.wp-site-blocks > .alignright { float: right; margin-left: 2em; }';
3049          $css .= '.wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }';
3050  
3051          // Block gap styles will be output unless explicitly set to `null`. See static::PROTECTED_PROPERTIES.
3052          if ( isset( $this->theme_json['settings']['spacing']['blockGap'] ) ) {
3053              $block_gap_value = static::get_property_value( $this->theme_json, array( 'styles', 'spacing', 'blockGap' ) );
3054              $css            .= ":where(.wp-site-blocks) > * { margin-block-start: $block_gap_value; margin-block-end: 0; }";
3055              $css            .= ':where(.wp-site-blocks) > :first-child { margin-block-start: 0; }';
3056              $css            .= ':where(.wp-site-blocks) > :last-child { margin-block-end: 0; }';
3057  
3058              // For backwards compatibility, ensure the legacy block gap CSS variable is still available.
3059              $css .= static::ROOT_CSS_PROPERTIES_SELECTOR . " { --wp--style--block-gap: $block_gap_value; }";
3060          }
3061          $css .= $this->get_layout_styles( $block_metadata );
3062  
3063          return $css;
3064      }
3065  
3066      /**
3067       * For metadata values that can either be booleans or paths to booleans, gets the value.
3068       *
3069       *     $data = array(
3070       *       'color' => array(
3071       *         'defaultPalette' => true
3072       *       )
3073       *     );
3074       *
3075       *     static::get_metadata_boolean( $data, false );
3076       *     // => false
3077       *
3078       *     static::get_metadata_boolean( $data, array( 'color', 'defaultPalette' ) );
3079       *     // => true
3080       *
3081       * @since 6.0.0
3082       *
3083       * @param array      $data          The data to inspect.
3084       * @param bool|array $path          Boolean or path to a boolean.
3085       * @param bool       $default_value Default value if the referenced path is missing.
3086       *                                  Default false.
3087       * @return bool Value of boolean metadata.
3088       */
3089  	protected static function get_metadata_boolean( $data, $path, $default_value = false ) {
3090          if ( is_bool( $path ) ) {
3091              return $path;
3092          }
3093  
3094          if ( is_array( $path ) ) {
3095              $value = _wp_array_get( $data, $path );
3096              if ( null !== $value ) {
3097                  return $value;
3098              }
3099          }
3100  
3101          return $default_value;
3102      }
3103  
3104      /**
3105       * Merges new incoming data.
3106       *
3107       * @since 5.8.0
3108       * @since 5.9.0 Duotone preset also has origins.
3109       * @since 6.7.0 Replace background image objects during merge.
3110       *
3111       * @param WP_Theme_JSON $incoming Data to merge.
3112       */
3113  	public function merge( $incoming ) {
3114          $incoming_data    = $incoming->get_raw_data();
3115          $this->theme_json = array_replace_recursive( $this->theme_json, $incoming_data );
3116  
3117          /*
3118           * Recompute all the spacing sizes based on the new hierarchy of data. In the constructor
3119           * spacingScale and spacingSizes are both keyed by origin and VALID_ORIGINS is ordered, so
3120           * we can allow partial spacingScale data to inherit missing data from earlier layers when
3121           * computing the spacing sizes.
3122           *
3123           * This happens before the presets are merged to ensure that default spacing sizes can be
3124           * removed from the theme origin if $prevent_override is true.
3125           */
3126          $flattened_spacing_scale = array();
3127          foreach ( static::VALID_ORIGINS as $origin ) {
3128              $scale_path = array( 'settings', 'spacing', 'spacingScale', $origin );
3129  
3130              // Apply the base spacing scale to the current layer.
3131              $base_spacing_scale      = _wp_array_get( $this->theme_json, $scale_path, array() );
3132              $flattened_spacing_scale = array_replace( $flattened_spacing_scale, $base_spacing_scale );
3133  
3134              $spacing_scale = _wp_array_get( $incoming_data, $scale_path, null );
3135              if ( ! isset( $spacing_scale ) ) {
3136                  continue;
3137              }
3138  
3139              // Allow partial scale settings by merging with lower layers.
3140              $flattened_spacing_scale = array_replace( $flattened_spacing_scale, $spacing_scale );
3141  
3142              // Generate and merge the scales for this layer.
3143              $sizes_path           = array( 'settings', 'spacing', 'spacingSizes', $origin );
3144              $spacing_sizes        = _wp_array_get( $incoming_data, $sizes_path, array() );
3145              $spacing_scale_sizes  = static::compute_spacing_sizes( $flattened_spacing_scale );
3146              $merged_spacing_sizes = static::merge_spacing_sizes( $spacing_scale_sizes, $spacing_sizes );
3147  
3148              _wp_array_set( $incoming_data, $sizes_path, $merged_spacing_sizes );
3149          }
3150  
3151          /*
3152           * The array_replace_recursive algorithm merges at the leaf level,
3153           * but we don't want leaf arrays to be merged, so we overwrite it.
3154           *
3155           * For leaf values that are sequential arrays it will use the numeric indexes for replacement.
3156           * We rather replace the existing with the incoming value, if it exists.
3157           * This is the case of spacing.units.
3158           *
3159           * For leaf values that are associative arrays it will merge them as expected.
3160           * This is also not the behavior we want for the current associative arrays (presets).
3161           * We rather replace the existing with the incoming value, if it exists.
3162           * This happens, for example, when we merge data from theme.json upon existing
3163           * theme supports or when we merge anything coming from the same source twice.
3164           * This is the case of color.palette, color.gradients, color.duotone,
3165           * typography.fontSizes, or typography.fontFamilies.
3166           *
3167           * Additionally, for some preset types, we also want to make sure the
3168           * values they introduce don't conflict with default values. We do so
3169           * by checking the incoming slugs for theme presets and compare them
3170           * with the equivalent default presets: if a slug is present as a default
3171           * we remove it from the theme presets.
3172           */
3173          $nodes        = static::get_setting_nodes( $incoming_data );
3174          $slugs_global = static::get_default_slugs( $this->theme_json, array( 'settings' ) );
3175          foreach ( $nodes as $node ) {
3176              // Replace the spacing.units.
3177              $path   = $node['path'];
3178              $path[] = 'spacing';
3179              $path[] = 'units';
3180  
3181              $content = _wp_array_get( $incoming_data, $path, null );
3182              if ( isset( $content ) ) {
3183                  _wp_array_set( $this->theme_json, $path, $content );
3184              }
3185  
3186              // Replace the presets.
3187              foreach ( static::PRESETS_METADATA as $preset_metadata ) {
3188                  $prevent_override = $preset_metadata['prevent_override'];
3189                  if ( is_array( $prevent_override ) ) {
3190                      $prevent_override = _wp_array_get( $this->theme_json['settings'], $preset_metadata['prevent_override'] );
3191                  }
3192  
3193                  foreach ( static::VALID_ORIGINS as $origin ) {
3194                      $base_path = $node['path'];
3195                      foreach ( $preset_metadata['path'] as $leaf ) {
3196                          $base_path[] = $leaf;
3197                      }
3198  
3199                      $path   = $base_path;
3200                      $path[] = $origin;
3201  
3202                      $content = _wp_array_get( $incoming_data, $path, null );
3203                      if ( ! isset( $content ) ) {
3204                          continue;
3205                      }
3206  
3207                      // Set names for theme presets based on the slug if they are not set and can use default names.
3208                      if ( 'theme' === $origin && $preset_metadata['use_default_names'] ) {
3209                          foreach ( $content as $key => $item ) {
3210                              if ( ! isset( $item['name'] ) ) {
3211                                  $name = static::get_name_from_defaults( $item['slug'], $base_path );
3212                                  if ( null !== $name ) {
3213                                      $content[ $key ]['name'] = $name;
3214                                  }
3215                              }
3216                          }
3217                      }
3218  
3219                      // Filter out default slugs from theme presets when defaults should not be overridden.
3220                      if ( 'theme' === $origin && $prevent_override ) {
3221                          $slugs_node    = static::get_default_slugs( $this->theme_json, $node['path'] );
3222                          $preset_global = _wp_array_get( $slugs_global, $preset_metadata['path'], array() );
3223                          $preset_node   = _wp_array_get( $slugs_node, $preset_metadata['path'], array() );
3224                          $preset_slugs  = array_merge_recursive( $preset_global, $preset_node );
3225  
3226                          $content = static::filter_slugs( $content, $preset_slugs );
3227                      }
3228  
3229                      _wp_array_set( $this->theme_json, $path, $content );
3230                  }
3231              }
3232          }
3233  
3234          /*
3235           * Style values are merged at the leaf level, however
3236           * some values provide exceptions, namely style values that are
3237           * objects and represent unique definitions for the style.
3238           */
3239          $style_nodes = static::get_styles_block_nodes();
3240          foreach ( $style_nodes as $style_node ) {
3241              $path = $style_node['path'];
3242              /*
3243               * Background image styles should be replaced, not merged,
3244               * as they themselves are specific object definitions for the style.
3245               */
3246              $background_image_path = array_merge( $path, static::PROPERTIES_METADATA['background-image'] );
3247              $content               = _wp_array_get( $incoming_data, $background_image_path, null );
3248              if ( isset( $content ) ) {
3249                  _wp_array_set( $this->theme_json, $background_image_path, $content );
3250              }
3251          }
3252      }
3253  
3254      /**
3255       * Converts all filter (duotone) presets into SVGs.
3256       *
3257       * @since 5.9.1
3258       *
3259       * @param array $origins List of origins to process.
3260       * @return string SVG filters.
3261       */
3262  	public function get_svg_filters( $origins ) {
3263          $blocks_metadata = static::get_blocks_metadata();
3264          $setting_nodes   = static::get_setting_nodes( $this->theme_json, $blocks_metadata );
3265  
3266          $filters = '';
3267          foreach ( $setting_nodes as $metadata ) {
3268              $node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
3269              if ( empty( $node['color']['duotone'] ) ) {
3270                  continue;
3271              }
3272  
3273              $duotone_presets = $node['color']['duotone'];
3274  
3275              foreach ( $origins as $origin ) {
3276                  if ( ! isset( $duotone_presets[ $origin ] ) ) {
3277                      continue;
3278                  }
3279                  foreach ( $duotone_presets[ $origin ] as $duotone_preset ) {
3280                      $filters .= wp_get_duotone_filter_svg( $duotone_preset );
3281                  }
3282              }
3283          }
3284  
3285          return $filters;
3286      }
3287  
3288      /**
3289       * Determines whether a presets should be overridden or not.
3290       *
3291       * @since 5.9.0
3292       * @deprecated 6.0.0 Use {@see 'get_metadata_boolean'} instead.
3293       *
3294       * @param array      $theme_json The theme.json like structure to inspect.
3295       * @param array      $path       Path to inspect.
3296       * @param bool|array $override   Data to compute whether to override the preset.
3297       * @return bool
3298       */
3299  	protected static function should_override_preset( $theme_json, $path, $override ) {
3300          _deprecated_function( __METHOD__, '6.0.0', 'get_metadata_boolean' );
3301  
3302          if ( is_bool( $override ) ) {
3303              return $override;
3304          }
3305  
3306          /*
3307           * The relationship between whether to override the defaults
3308           * and whether the defaults are enabled is inverse:
3309           *
3310           * - If defaults are enabled  => theme presets should not be overridden
3311           * - If defaults are disabled => theme presets should be overridden
3312           *
3313           * For example, a theme sets defaultPalette to false,
3314           * making the default palette hidden from the user.
3315           * In that case, we want all the theme presets to be present,
3316           * so they should override the defaults.
3317           */
3318          if ( is_array( $override ) ) {
3319              $value = _wp_array_get( $theme_json, array_merge( $path, $override ) );
3320              if ( isset( $value ) ) {
3321                  return ! $value;
3322              }
3323  
3324              // Search the top-level key if none was found for this node.
3325              $value = _wp_array_get( $theme_json, array_merge( array( 'settings' ), $override ) );
3326              if ( isset( $value ) ) {
3327                  return ! $value;
3328              }
3329  
3330              return true;
3331          }
3332      }
3333  
3334      /**
3335       * Returns the default slugs for all the presets in an associative array
3336       * whose keys are the preset paths and the leaves is the list of slugs.
3337       *
3338       * For example:
3339       *
3340       *     array(
3341       *       'color' => array(
3342       *         'palette'   => array( 'slug-1', 'slug-2' ),
3343       *         'gradients' => array( 'slug-3', 'slug-4' ),
3344       *       ),
3345       *     )
3346       *
3347       * @since 5.9.0
3348       *
3349       * @param array $data      A theme.json like structure.
3350       * @param array $node_path The path to inspect. It's 'settings' by default.
3351       * @return array
3352       */
3353  	protected static function get_default_slugs( $data, $node_path ) {
3354          $slugs = array();
3355  
3356          foreach ( static::PRESETS_METADATA as $metadata ) {
3357              $path = $node_path;
3358              foreach ( $metadata['path'] as $leaf ) {
3359                  $path[] = $leaf;
3360              }
3361              $path[] = 'default';
3362  
3363              $preset = _wp_array_get( $data, $path, null );
3364              if ( ! isset( $preset ) ) {
3365                  continue;
3366              }
3367  
3368              $slugs_for_preset = array();
3369              foreach ( $preset as $item ) {
3370                  if ( isset( $item['slug'] ) ) {
3371                      $slugs_for_preset[] = $item['slug'];
3372                  }
3373              }
3374  
3375              _wp_array_set( $slugs, $metadata['path'], $slugs_for_preset );
3376          }
3377  
3378          return $slugs;
3379      }
3380  
3381      /**
3382       * Gets a `default`'s preset name by a provided slug.
3383       *
3384       * @since 5.9.0
3385       *
3386       * @param string $slug The slug we want to find a match from default presets.
3387       * @param array  $base_path The path to inspect. It's 'settings' by default.
3388       * @return string|null
3389       */
3390  	protected function get_name_from_defaults( $slug, $base_path ) {
3391          $path            = $base_path;
3392          $path[]          = 'default';
3393          $default_content = _wp_array_get( $this->theme_json, $path, null );
3394          if ( ! $default_content ) {
3395              return null;
3396          }
3397          foreach ( $default_content as $item ) {
3398              if ( $slug === $item['slug'] ) {
3399                  return $item['name'];
3400              }
3401          }
3402          return null;
3403      }
3404  
3405      /**
3406       * Removes the preset values whose slug is equal to any of given slugs.
3407       *
3408       * @since 5.9.0
3409       *
3410       * @param array $node  The node with the presets to validate.
3411       * @param array $slugs The slugs that should not be overridden.
3412       * @return array The new node.
3413       */
3414  	protected static function filter_slugs( $node, $slugs ) {
3415          if ( empty( $slugs ) ) {
3416              return $node;
3417          }
3418  
3419          $new_node = array();
3420          foreach ( $node as $value ) {
3421              if ( isset( $value['slug'] ) && ! in_array( $value['slug'], $slugs, true ) ) {
3422                  $new_node[] = $value;
3423              }
3424          }
3425  
3426          return $new_node;
3427      }
3428  
3429      /**
3430       * Removes insecure data from theme.json.
3431       *
3432       * @since 5.9.0
3433       * @since 6.3.2 Preserves global styles block variations when securing styles.
3434       * @since 6.6.0 Updated to allow variation element styles and $origin parameter.
3435       *
3436       * @param array  $theme_json Structure to sanitize.
3437       * @param string $origin    Optional. What source of data this object represents.
3438       *                          One of 'blocks', 'default', 'theme', or 'custom'. Default 'theme'.
3439       * @return array Sanitized structure.
3440       */
3441  	public static function remove_insecure_properties( $theme_json, $origin = 'theme' ) {
3442          if ( ! in_array( $origin, static::VALID_ORIGINS, true ) ) {
3443              $origin = 'theme';
3444          }
3445  
3446          $sanitized = array();
3447  
3448          $theme_json = WP_Theme_JSON_Schema::migrate( $theme_json, $origin );
3449  
3450          $valid_block_names   = array_keys( static::get_blocks_metadata() );
3451          $valid_element_names = array_keys( static::ELEMENTS );
3452          $valid_variations    = static::get_valid_block_style_variations();
3453  
3454          $theme_json = static::sanitize( $theme_json, $valid_block_names, $valid_element_names, $valid_variations );
3455  
3456          $blocks_metadata = static::get_blocks_metadata();
3457          $style_options   = array( 'include_block_style_variations' => true ); // Allow variations data.
3458          $style_nodes     = static::get_style_nodes( $theme_json, $blocks_metadata, $style_options );
3459  
3460          foreach ( $style_nodes as $metadata ) {
3461              $input = _wp_array_get( $theme_json, $metadata['path'], array() );
3462              if ( empty( $input ) ) {
3463                  continue;
3464              }
3465  
3466              // The global styles custom CSS is not sanitized, but can only be edited by users with 'edit_css' capability.
3467              if ( isset( $input['css'] ) && current_user_can( 'edit_css' ) ) {
3468                  $output = $input;
3469              } else {
3470                  $output = static::remove_insecure_styles( $input );
3471              }
3472  
3473              /*
3474               * Get a reference to element name from path.
3475               * $metadata['path'] = array( 'styles', 'elements', 'link' );
3476               */
3477              $current_element = $metadata['path'][ count( $metadata['path'] ) - 1 ];
3478  
3479              /*
3480               * $output is stripped of pseudo selectors. Re-add and process them
3481               * or insecure styles here.
3482               */
3483              if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) ) {
3484                  foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] as $pseudo_selector ) {
3485                      if ( isset( $input[ $pseudo_selector ] ) ) {
3486                          $output[ $pseudo_selector ] = static::remove_insecure_styles( $input[ $pseudo_selector ] );
3487                      }
3488                  }
3489              }
3490  
3491              if ( ! empty( $output ) ) {
3492                  _wp_array_set( $sanitized, $metadata['path'], $output );
3493              }
3494  
3495              if ( isset( $metadata['variations'] ) ) {
3496                  foreach ( $metadata['variations'] as $variation ) {
3497                      $variation_input = _wp_array_get( $theme_json, $variation['path'], array() );
3498                      if ( empty( $variation_input ) ) {
3499                          continue;
3500                      }
3501  
3502                      $variation_output = static::remove_insecure_styles( $variation_input );
3503  
3504                      // Process a variation's elements and element pseudo selector styles.
3505                      if ( isset( $variation_input['elements'] ) ) {
3506                          foreach ( $valid_element_names as $element_name ) {
3507                              $element_input = $variation_input['elements'][ $element_name ] ?? null;
3508                              if ( $element_input ) {
3509                                  $element_output = static::remove_insecure_styles( $element_input );
3510  
3511                                  if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] ) ) {
3512                                      foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] as $pseudo_selector ) {
3513                                          if ( isset( $element_input[ $pseudo_selector ] ) ) {
3514                                              $element_output[ $pseudo_selector ] = static::remove_insecure_styles( $element_input[ $pseudo_selector ] );
3515                                          }
3516                                      }
3517                                  }
3518  
3519                                  if ( ! empty( $element_output ) ) {
3520                                      _wp_array_set( $variation_output, array( 'elements', $element_name ), $element_output );
3521                                  }
3522                              }
3523                          }
3524                      }
3525  
3526                      if ( ! empty( $variation_output ) ) {
3527                          _wp_array_set( $sanitized, $variation['path'], $variation_output );
3528                      }
3529                  }
3530              }
3531          }
3532  
3533          $setting_nodes = static::get_setting_nodes( $theme_json );
3534          foreach ( $setting_nodes as $metadata ) {
3535              $input = _wp_array_get( $theme_json, $metadata['path'], array() );
3536              if ( empty( $input ) ) {
3537                  continue;
3538              }
3539  
3540              $output = static::remove_insecure_settings( $input );
3541              if ( ! empty( $output ) ) {
3542                  _wp_array_set( $sanitized, $metadata['path'], $output );
3543              }
3544          }
3545  
3546          if ( empty( $sanitized['styles'] ) ) {
3547              unset( $theme_json['styles'] );
3548          } else {
3549              $theme_json['styles'] = $sanitized['styles'];
3550          }
3551  
3552          if ( empty( $sanitized['settings'] ) ) {
3553              unset( $theme_json['settings'] );
3554          } else {
3555              $theme_json['settings'] = $sanitized['settings'];
3556          }
3557  
3558          return $theme_json;
3559      }
3560  
3561      /**
3562       * Processes a setting node and returns the same node
3563       * without the insecure settings.
3564       *
3565       * @since 5.9.0
3566       *
3567       * @param array $input Node to process.
3568       * @return array
3569       */
3570  	protected static function remove_insecure_settings( $input ) {
3571          $output = array();
3572          foreach ( static::PRESETS_METADATA as $preset_metadata ) {
3573              foreach ( static::VALID_ORIGINS as $origin ) {
3574                  $path_with_origin   = $preset_metadata['path'];
3575                  $path_with_origin[] = $origin;
3576                  $presets            = _wp_array_get( $input, $path_with_origin, null );
3577                  if ( null === $presets ) {
3578                      continue;
3579                  }
3580  
3581                  $escaped_preset = array();
3582                  foreach ( $presets as $preset ) {
3583                      if (
3584                          esc_attr( esc_html( $preset['name'] ) ) === $preset['name'] &&
3585                          sanitize_html_class( $preset['slug'] ) === $preset['slug']
3586                      ) {
3587                          $value = null;
3588                          if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) {
3589                              $value = $preset[ $preset_metadata['value_key'] ];
3590                          } elseif (
3591                              isset( $preset_metadata['value_func'] ) &&
3592                              is_callable( $preset_metadata['value_func'] )
3593                          ) {
3594                              $value = call_user_func( $preset_metadata['value_func'], $preset );
3595                          }
3596  
3597                          $preset_is_valid = true;
3598                          foreach ( $preset_metadata['properties'] as $property ) {
3599                              if ( ! static::is_safe_css_declaration( $property, $value ) ) {
3600                                  $preset_is_valid = false;
3601                                  break;
3602                              }
3603                          }
3604  
3605                          if ( $preset_is_valid ) {
3606                              $escaped_preset[] = $preset;
3607                          }
3608                      }
3609                  }
3610  
3611                  if ( ! empty( $escaped_preset ) ) {
3612                      _wp_array_set( $output, $path_with_origin, $escaped_preset );
3613                  }
3614              }
3615          }
3616  
3617          // Ensure indirect properties not included in any `PRESETS_METADATA` value are allowed.
3618          static::remove_indirect_properties( $input, $output );
3619  
3620          return $output;
3621      }
3622  
3623      /**
3624       * Processes a style node and returns the same node
3625       * without the insecure styles.
3626       *
3627       * @since 5.9.0
3628       *
3629       * @param array $input Node to process.
3630       * @return array
3631       */
3632  	protected static function remove_insecure_styles( $input ) {
3633          $output       = array();
3634          $declarations = static::compute_style_properties( $input );
3635  
3636          foreach ( $declarations as $declaration ) {
3637              if ( static::is_safe_css_declaration( $declaration['name'], $declaration['value'] ) ) {
3638                  $path = static::PROPERTIES_METADATA[ $declaration['name'] ];
3639  
3640                  /*
3641                   * Check the value isn't an array before adding so as to not
3642                   * double up shorthand and longhand styles.
3643                   */
3644                  $value = _wp_array_get( $input, $path, array() );
3645                  if ( ! is_array( $value ) ) {
3646                      _wp_array_set( $output, $path, $value );
3647                  }
3648              }
3649          }
3650  
3651          // Ensure indirect properties not handled by `compute_style_properties` are allowed.
3652          static::remove_indirect_properties( $input, $output );
3653  
3654          return $output;
3655      }
3656  
3657      /**
3658       * Checks that a declaration provided by the user is safe.
3659       *
3660       * @since 5.9.0
3661       *
3662       * @param string $property_name  Property name in a CSS declaration, i.e. the `color` in `color: red`.
3663       * @param string $property_value Value in a CSS declaration, i.e. the `red` in `color: red`.
3664       * @return bool
3665       */
3666  	protected static function is_safe_css_declaration( $property_name, $property_value ) {
3667          $style_to_validate = $property_name . ': ' . $property_value;
3668          $filtered          = esc_html( safecss_filter_attr( $style_to_validate ) );
3669          return ! empty( trim( $filtered ) );
3670      }
3671  
3672      /**
3673       * Removes indirect properties from the given input node and
3674       * sets in the given output node.
3675       *
3676       * @since 6.2.0
3677       *
3678       * @param array $input  Node to process.
3679       * @param array $output The processed node. Passed by reference.
3680       */
3681  	private static function remove_indirect_properties( $input, &$output ) {
3682          foreach ( static::INDIRECT_PROPERTIES_METADATA as $property => $paths ) {
3683              foreach ( $paths as $path ) {
3684                  $value = _wp_array_get( $input, $path );
3685                  if (
3686                      is_string( $value ) &&
3687                      static::is_safe_css_declaration( $property, $value )
3688                  ) {
3689                      _wp_array_set( $output, $path, $value );
3690                  }
3691              }
3692          }
3693      }
3694  
3695      /**
3696       * Returns the raw data.
3697       *
3698       * @since 5.8.0
3699       *
3700       * @return array Raw data.
3701       */
3702  	public function get_raw_data() {
3703          return $this->theme_json;
3704      }
3705  
3706      /**
3707       * Transforms the given editor settings according the
3708       * add_theme_support format to the theme.json format.
3709       *
3710       * @since 5.8.0
3711       *
3712       * @param array $settings Existing editor settings.
3713       * @return array Config that adheres to the theme.json schema.
3714       */
3715  	public static function get_from_editor_settings( $settings ) {
3716          $theme_settings = array(
3717              'version'  => static::LATEST_SCHEMA,
3718              'settings' => array(),
3719          );
3720  
3721          // Deprecated theme supports.
3722          if ( isset( $settings['disableCustomColors'] ) ) {
3723              $theme_settings['settings']['color']['custom'] = ! $settings['disableCustomColors'];
3724          }
3725  
3726          if ( isset( $settings['disableCustomGradients'] ) ) {
3727              $theme_settings['settings']['color']['customGradient'] = ! $settings['disableCustomGradients'];
3728          }
3729  
3730          if ( isset( $settings['disableCustomFontSizes'] ) ) {
3731              $theme_settings['settings']['typography']['customFontSize'] = ! $settings['disableCustomFontSizes'];
3732          }
3733  
3734          if ( isset( $settings['enableCustomLineHeight'] ) ) {
3735              $theme_settings['settings']['typography']['lineHeight'] = $settings['enableCustomLineHeight'];
3736          }
3737  
3738          if ( isset( $settings['enableCustomUnits'] ) ) {
3739              $theme_settings['settings']['spacing']['units'] = ( true === $settings['enableCustomUnits'] ) ?
3740                  array( 'px', 'em', 'rem', 'vh', 'vw', '%' ) :
3741                  $settings['enableCustomUnits'];
3742          }
3743  
3744          if ( isset( $settings['colors'] ) ) {
3745              $theme_settings['settings']['color']['palette'] = $settings['colors'];
3746          }
3747  
3748          if ( isset( $settings['gradients'] ) ) {
3749              $theme_settings['settings']['color']['gradients'] = $settings['gradients'];
3750          }
3751  
3752          if ( isset( $settings['fontSizes'] ) ) {
3753              $font_sizes = $settings['fontSizes'];
3754              // Back-compatibility for presets without units.
3755              foreach ( $font_sizes as $key => $font_size ) {
3756                  if ( is_numeric( $font_size['size'] ) ) {
3757                      $font_sizes[ $key ]['size'] = $font_size['size'] . 'px';
3758                  }
3759              }
3760              $theme_settings['settings']['typography']['fontSizes'] = $font_sizes;
3761          }
3762  
3763          if ( isset( $settings['enableCustomSpacing'] ) ) {
3764              $theme_settings['settings']['spacing']['padding'] = $settings['enableCustomSpacing'];
3765          }
3766  
3767          if ( isset( $settings['spacingSizes'] ) ) {
3768              $theme_settings['settings']['spacing']['spacingSizes'] = $settings['spacingSizes'];
3769          }
3770  
3771          return $theme_settings;
3772      }
3773  
3774      /**
3775       * Returns the current theme's wanted patterns(slugs) to be
3776       * registered from Pattern Directory.
3777       *
3778       * @since 6.0.0
3779       *
3780       * @return string[]
3781       */
3782  	public function get_patterns() {
3783          if ( isset( $this->theme_json['patterns'] ) && is_array( $this->theme_json['patterns'] ) ) {
3784              return $this->theme_json['patterns'];
3785          }
3786          return array();
3787      }
3788  
3789      /**
3790       * Returns a valid theme.json as provided by a theme.
3791       *
3792       * Unlike get_raw_data() this returns the presets flattened, as provided by a theme.
3793       * This also uses appearanceTools instead of their opt-ins if all of them are true.
3794       *
3795       * @since 6.0.0
3796       *
3797       * @return array
3798       */
3799  	public function get_data() {
3800          $output = $this->theme_json;
3801          $nodes  = static::get_setting_nodes( $output );
3802  
3803          /**
3804           * Flatten the theme & custom origins into a single one.
3805           *
3806           * For example, the following:
3807           *
3808           * {
3809           *   "settings": {
3810           *     "color": {
3811           *       "palette": {
3812           *         "theme": [ {} ],
3813           *         "custom": [ {} ]
3814           *       }
3815           *     }
3816           *   }
3817           * }
3818           *
3819           * will be converted to:
3820           *
3821           * {
3822           *   "settings": {
3823           *     "color": {
3824           *       "palette": [ {} ]
3825           *     }
3826           *   }
3827           * }
3828           */
3829          foreach ( $nodes as $node ) {
3830              foreach ( static::PRESETS_METADATA as $preset_metadata ) {
3831                  $path = $node['path'];
3832                  foreach ( $preset_metadata['path'] as $preset_metadata_path ) {
3833                      $path[] = $preset_metadata_path;
3834                  }
3835                  $preset = _wp_array_get( $output, $path, null );
3836                  if ( null === $preset ) {
3837                      continue;
3838                  }
3839  
3840                  $items = array();
3841                  if ( isset( $preset['theme'] ) ) {
3842                      foreach ( $preset['theme'] as $item ) {
3843                          $slug = $item['slug'];
3844                          unset( $item['slug'] );
3845                          $items[ $slug ] = $item;
3846                      }
3847                  }
3848                  if ( isset( $preset['custom'] ) ) {
3849                      foreach ( $preset['custom'] as $item ) {
3850                          $slug = $item['slug'];
3851                          unset( $item['slug'] );
3852                          $items[ $slug ] = $item;
3853                      }
3854                  }
3855                  $flattened_preset = array();
3856                  foreach ( $items as $slug => $value ) {
3857                      $flattened_preset[] = array_merge( array( 'slug' => (string) $slug ), $value );
3858                  }
3859                  _wp_array_set( $output, $path, $flattened_preset );
3860              }
3861          }
3862  
3863          /*
3864           * If all of the static::APPEARANCE_TOOLS_OPT_INS are true,
3865           * this code unsets them and sets 'appearanceTools' instead.
3866           */
3867          foreach ( $nodes as $node ) {
3868              $all_opt_ins_are_set = true;
3869              foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) {
3870                  $full_path = $node['path'];
3871                  foreach ( $opt_in_path as $opt_in_path_item ) {
3872                      $full_path[] = $opt_in_path_item;
3873                  }
3874                  /*
3875                   * Use "unset prop" as a marker instead of "null" because
3876                   * "null" can be a valid value for some props (e.g. blockGap).
3877                   */
3878                  $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' );
3879                  if ( 'unset prop' === $opt_in_value ) {
3880                      $all_opt_ins_are_set = false;
3881                      break;
3882                  }
3883              }
3884  
3885              if ( $all_opt_ins_are_set ) {
3886                  $node_path_with_appearance_tools   = $node['path'];
3887                  $node_path_with_appearance_tools[] = 'appearanceTools';
3888                  _wp_array_set( $output, $node_path_with_appearance_tools, true );
3889                  foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) {
3890                      $full_path = $node['path'];
3891                      foreach ( $opt_in_path as $opt_in_path_item ) {
3892                          $full_path[] = $opt_in_path_item;
3893                      }
3894                      /*
3895                       * Use "unset prop" as a marker instead of "null" because
3896                       * "null" can be a valid value for some props (e.g. blockGap).
3897                       */
3898                      $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' );
3899                      if ( true !== $opt_in_value ) {
3900                          continue;
3901                      }
3902  
3903                      /*
3904                       * The following could be improved to be path independent.
3905                       * At the moment it relies on a couple of assumptions:
3906                       *
3907                       * - all opt-ins having a path of size 2.
3908                       * - there's two sources of settings: the top-level and the block-level.
3909                       */
3910                      if (
3911                          ( 1 === count( $node['path'] ) ) &&
3912                          ( 'settings' === $node['path'][0] )
3913                      ) {
3914                          // Top-level settings.
3915                          unset( $output['settings'][ $opt_in_path[0] ][ $opt_in_path[1] ] );
3916                          if ( empty( $output['settings'][ $opt_in_path[0] ] ) ) {
3917                              unset( $output['settings'][ $opt_in_path[0] ] );
3918                          }
3919                      } elseif (
3920                          ( 3 === count( $node['path'] ) ) &&
3921                          ( 'settings' === $node['path'][0] ) &&
3922                          ( 'blocks' === $node['path'][1] )
3923                      ) {
3924                          // Block-level settings.
3925                          $block_name = $node['path'][2];
3926                          unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ][ $opt_in_path[1] ] );
3927                          if ( empty( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] ) ) {
3928                              unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] );
3929                          }
3930                      }
3931                  }
3932              }
3933          }
3934  
3935          wp_recursive_ksort( $output );
3936  
3937          return $output;
3938      }
3939  
3940      /**
3941       * Sets the spacingSizes array based on the spacingScale values from theme.json.
3942       *
3943       * @since 6.1.0
3944       * @deprecated 6.6.0 No longer used as the spacingSizes are automatically
3945       *                   generated in the constructor and merge methods instead
3946       *                   of manually after instantiation.
3947       *
3948       * @return null|void
3949       */
3950  	public function set_spacing_sizes() {
3951          _deprecated_function( __METHOD__, '6.6.0' );
3952  
3953          $spacing_scale = isset( $this->theme_json['settings']['spacing']['spacingScale'] )
3954              ? $this->theme_json['settings']['spacing']['spacingScale']
3955              : array();
3956  
3957          if ( ! isset( $spacing_scale['steps'] )
3958              || ! is_numeric( $spacing_scale['steps'] )
3959              || ! isset( $spacing_scale['mediumStep'] )
3960              || ! isset( $spacing_scale['unit'] )
3961              || ! isset( $spacing_scale['operator'] )
3962              || ! isset( $spacing_scale['increment'] )
3963              || ! isset( $spacing_scale['steps'] )
3964              || ! is_numeric( $spacing_scale['increment'] )
3965              || ! is_numeric( $spacing_scale['mediumStep'] )
3966              || ( '+' !== $spacing_scale['operator'] && '*' !== $spacing_scale['operator'] ) ) {
3967              if ( ! empty( $spacing_scale ) ) {
3968                  wp_trigger_error(
3969                      __METHOD__,
3970                      sprintf(
3971                          /* translators: 1: theme.json, 2: settings.spacing.spacingScale */
3972                          __( 'Some of the %1$s %2$s values are invalid' ),
3973                          'theme.json',
3974                          'settings.spacing.spacingScale'
3975                      ),
3976                      E_USER_NOTICE
3977                  );
3978              }
3979              return null;
3980          }
3981  
3982          // If theme authors want to prevent the generation of the core spacing scale they can set their theme.json spacingScale.steps to 0.
3983          if ( 0 === $spacing_scale['steps'] ) {
3984              return null;
3985          }
3986  
3987          $spacing_sizes = static::compute_spacing_sizes( $spacing_scale );
3988  
3989          // If there are 7 or fewer steps in the scale revert to numbers for labels instead of t-shirt sizes.
3990          if ( $spacing_scale['steps'] <= 7 ) {
3991              for ( $spacing_sizes_count = 0; $spacing_sizes_count < count( $spacing_sizes ); $spacing_sizes_count++ ) {
3992                  $spacing_sizes[ $spacing_sizes_count ]['name'] = (string) ( $spacing_sizes_count + 1 );
3993              }
3994          }
3995  
3996          _wp_array_set( $this->theme_json, array( 'settings', 'spacing', 'spacingSizes', 'default' ), $spacing_sizes );
3997      }
3998  
3999      /**
4000       * Merges two sets of spacing size presets.
4001       *
4002       * @since 6.6.0
4003       *
4004       * @param array $base     The base set of spacing sizes.
4005       * @param array $incoming The set of spacing sizes to merge with the base. Duplicate slugs will override the base values.
4006       * @return array The merged set of spacing sizes.
4007       */
4008  	private static function merge_spacing_sizes( $base, $incoming ) {
4009          // Preserve the order if there are no base (spacingScale) values.
4010          if ( empty( $base ) ) {
4011              return $incoming;
4012          }
4013          $merged = array();
4014          foreach ( $base as $item ) {
4015              $merged[ $item['slug'] ] = $item;
4016          }
4017          foreach ( $incoming as $item ) {
4018              $merged[ $item['slug'] ] = $item;
4019          }
4020          ksort( $merged, SORT_NUMERIC );
4021          return array_values( $merged );
4022      }
4023  
4024      /**
4025       * Generates a set of spacing sizes by starting with a medium size and
4026       * applying an operator with an increment value to generate the rest of the
4027       * sizes outward from the medium size. The medium slug is '50' with the rest
4028       * of the slugs being 10 apart. The generated names use t-shirt sizing.
4029       *
4030       * Example:
4031       *
4032       *     $spacing_scale = array(
4033       *         'steps'      => 4,
4034       *         'mediumStep' => 16,
4035       *         'unit'       => 'px',
4036       *         'operator'   => '+',
4037       *         'increment'  => 2,
4038       *     );
4039       *     $spacing_sizes = static::compute_spacing_sizes( $spacing_scale );
4040       *     // -> array(
4041       *     //        array( 'name' => 'Small',   'slug' => '40', 'size' => '14px' ),
4042       *     //        array( 'name' => 'Medium',  'slug' => '50', 'size' => '16px' ),
4043       *     //        array( 'name' => 'Large',   'slug' => '60', 'size' => '18px' ),
4044       *     //        array( 'name' => 'X-Large', 'slug' => '70', 'size' => '20px' ),
4045       *     //    )
4046       *
4047       * @since 6.6.0
4048       *
4049       * @param array $spacing_scale {
4050       *      The spacing scale values. All are required.
4051       *
4052       *      @type int    $steps      The number of steps in the scale. (up to 10 steps are supported.)
4053       *      @type float  $mediumStep The middle value that gets the slug '50'. (For even number of steps, this becomes the first middle value.)
4054       *      @type string $unit       The CSS unit to use for the sizes.
4055       *      @type string $operator   The mathematical operator to apply to generate the other sizes. Either '+' or '*'.
4056       *      @type float  $increment  The value used with the operator to generate the other sizes.
4057       * }
4058       * @return array The spacing sizes presets or an empty array if some spacing scale values are missing or invalid.
4059       */
4060  	private static function compute_spacing_sizes( $spacing_scale ) {
4061          /*
4062           * This condition is intentionally missing some checks on ranges for the values in order to
4063           * keep backwards compatibility with the previous implementation.
4064           */
4065          if (
4066              ! isset( $spacing_scale['steps'] ) ||
4067              ! is_numeric( $spacing_scale['steps'] ) ||
4068              0 === $spacing_scale['steps'] ||
4069              ! isset( $spacing_scale['mediumStep'] ) ||
4070              ! is_numeric( $spacing_scale['mediumStep'] ) ||
4071              ! isset( $spacing_scale['unit'] ) ||
4072              ! isset( $spacing_scale['operator'] ) ||
4073              ( '+' !== $spacing_scale['operator'] && '*' !== $spacing_scale['operator'] ) ||
4074              ! isset( $spacing_scale['increment'] ) ||
4075              ! is_numeric( $spacing_scale['increment'] )
4076          ) {
4077              return array();
4078          }
4079  
4080          $unit            = '%' === $spacing_scale['unit'] ? '%' : sanitize_title( $spacing_scale['unit'] );
4081          $current_step    = $spacing_scale['mediumStep'];
4082          $steps_mid_point = round( $spacing_scale['steps'] / 2, 0 );
4083          $x_small_count   = null;
4084          $below_sizes     = array();
4085          $slug            = 40;
4086          $remainder       = 0;
4087  
4088          for ( $below_midpoint_count = $steps_mid_point - 1; $spacing_scale['steps'] > 1 && $slug > 0 && $below_midpoint_count > 0; $below_midpoint_count-- ) {
4089              if ( '+' === $spacing_scale['operator'] ) {
4090                  $current_step -= $spacing_scale['increment'];
4091              } elseif ( $spacing_scale['increment'] > 1 ) {
4092                  $current_step /= $spacing_scale['increment'];
4093              } else {
4094                  $current_step *= $spacing_scale['increment'];
4095              }
4096  
4097              if ( $current_step <= 0 ) {
4098                  $remainder = $below_midpoint_count;
4099                  break;
4100              }
4101  
4102              $below_sizes[] = array(
4103                  /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Small. */
4104                  'name' => $below_midpoint_count === $steps_mid_point - 1 ? __( 'Small' ) : sprintf( __( '%sX-Small' ), (string) $x_small_count ),
4105                  'slug' => (string) $slug,
4106                  'size' => round( $current_step, 2 ) . $unit,
4107              );
4108  
4109              if ( $below_midpoint_count === $steps_mid_point - 2 ) {
4110                  $x_small_count = 2;
4111              }
4112  
4113              if ( $below_midpoint_count < $steps_mid_point - 2 ) {
4114                  ++$x_small_count;
4115              }
4116  
4117              $slug -= 10;
4118          }
4119  
4120          $below_sizes = array_reverse( $below_sizes );
4121  
4122          $below_sizes[] = array(
4123              'name' => __( 'Medium' ),
4124              'slug' => '50',
4125              'size' => $spacing_scale['mediumStep'] . $unit,
4126          );
4127  
4128          $current_step  = $spacing_scale['mediumStep'];
4129          $x_large_count = null;
4130          $above_sizes   = array();
4131          $slug          = 60;
4132          $steps_above   = ( $spacing_scale['steps'] - $steps_mid_point ) + $remainder;
4133  
4134          for ( $above_midpoint_count = 0; $above_midpoint_count < $steps_above; $above_midpoint_count++ ) {
4135              $current_step = '+' === $spacing_scale['operator']
4136                  ? $current_step + $spacing_scale['increment']
4137                  : ( $spacing_scale['increment'] >= 1 ? $current_step * $spacing_scale['increment'] : $current_step / $spacing_scale['increment'] );
4138  
4139              $above_sizes[] = array(
4140                  /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Large. */
4141                  'name' => 0 === $above_midpoint_count ? __( 'Large' ) : sprintf( __( '%sX-Large' ), (string) $x_large_count ),
4142                  'slug' => (string) $slug,
4143                  'size' => round( $current_step, 2 ) . $unit,
4144              );
4145  
4146              if ( 1 === $above_midpoint_count ) {
4147                  $x_large_count = 2;
4148              }
4149  
4150              if ( $above_midpoint_count > 1 ) {
4151                  ++$x_large_count;
4152              }
4153  
4154              $slug += 10;
4155          }
4156  
4157          $spacing_sizes = $below_sizes;
4158          foreach ( $above_sizes as $above_sizes_item ) {
4159              $spacing_sizes[] = $above_sizes_item;
4160          }
4161  
4162          return $spacing_sizes;
4163      }
4164  
4165      /**
4166       * This is used to convert the internal representation of variables to the CSS representation.
4167       * For example, `var:preset|color|vivid-green-cyan` becomes `var(--wp--preset--color--vivid-green-cyan)`.
4168       *
4169       * @since 6.3.0
4170       * @param string $value The variable such as var:preset|color|vivid-green-cyan to convert.
4171       * @return string The converted variable.
4172       */
4173  	private static function convert_custom_properties( $value ) {
4174          $prefix     = 'var:';
4175          $prefix_len = strlen( $prefix );
4176          $token_in   = '|';
4177          $token_out  = '--';
4178          if ( str_starts_with( $value, $prefix ) ) {
4179              $unwrapped_name = str_replace(
4180                  $token_in,
4181                  $token_out,
4182                  substr( $value, $prefix_len )
4183              );
4184              $value          = "var(--wp--$unwrapped_name)";
4185          }
4186  
4187          return $value;
4188      }
4189  
4190      /**
4191       * Given a tree, converts the internal representation of variables to the CSS representation.
4192       * It is recursive and modifies the input in-place.
4193       *
4194       * @since 6.3.0
4195       * @param array $tree   Input to process.
4196       * @return array The modified $tree.
4197       */
4198  	private static function resolve_custom_css_format( $tree ) {
4199          $prefix = 'var:';
4200  
4201          foreach ( $tree as $key => $data ) {
4202              if ( is_string( $data ) && str_starts_with( $data, $prefix ) ) {
4203                  $tree[ $key ] = self::convert_custom_properties( $data );
4204              } elseif ( is_array( $data ) ) {
4205                  $tree[ $key ] = self::resolve_custom_css_format( $data );
4206              }
4207          }
4208  
4209          return $tree;
4210      }
4211  
4212      /**
4213       * Returns the selectors metadata for a block.
4214       *
4215       * @since 6.3.0
4216       *
4217       * @param object $block_type    The block type.
4218       * @param string $root_selector The block's root selector.
4219       *
4220       * @return array The custom selectors set by the block.
4221       */
4222  	protected static function get_block_selectors( $block_type, $root_selector ) {
4223          if ( ! empty( $block_type->selectors ) ) {
4224              return $block_type->selectors;
4225          }
4226  
4227          $selectors = array( 'root' => $root_selector );
4228          foreach ( static::BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS as $key => $feature ) {
4229              $feature_selector = wp_get_block_css_selector( $block_type, $key );
4230              if ( null !== $feature_selector ) {
4231                  $selectors[ $feature ] = array( 'root' => $feature_selector );
4232              }
4233          }
4234  
4235          return $selectors;
4236      }
4237  
4238      /**
4239       * Generates all the element selectors for a block.
4240       *
4241       * @since 6.3.0
4242       *
4243       * @param string $root_selector The block's root CSS selector.
4244       * @return array The block's element selectors.
4245       */
4246  	protected static function get_block_element_selectors( $root_selector ) {
4247          /*
4248           * Assign defaults, then override those that the block sets by itself.
4249           * If the block selector is compounded, will append the element to each
4250           * individual block selector.
4251           */
4252          $block_selectors   = explode( ',', $root_selector );
4253          $element_selectors = array();
4254          foreach ( static::ELEMENTS as $el_name => $el_selector ) {
4255              $element_selector = array();
4256              foreach ( $block_selectors as $selector ) {
4257                  if ( $selector === $el_selector ) {
4258                      $element_selector = array( $el_selector );
4259                      break;
4260                  }
4261                  $element_selector[] = static::prepend_to_selector( $el_selector, $selector . ' ' );
4262              }
4263              $element_selectors[ $el_name ] = implode( ',', $element_selector );
4264          }
4265  
4266          return $element_selectors;
4267      }
4268  
4269      /**
4270       * Generates style declarations for a node's features e.g., color, border,
4271       * typography etc. that have custom selectors in their related block's
4272       * metadata.
4273       *
4274       * @since 6.3.0
4275       *
4276       * @param object $metadata The related block metadata containing selectors.
4277       * @param object $node     A merged theme.json node for block or variation.
4278       *
4279       * @return array The style declarations for the node's features with custom
4280       * selectors.
4281       */
4282  	protected function get_feature_declarations_for_node( $metadata, &$node ) {
4283          $declarations = array();
4284  
4285          if ( ! isset( $metadata['selectors'] ) ) {
4286              return $declarations;
4287          }
4288  
4289          $settings = isset( $this->theme_json['settings'] )
4290              ? $this->theme_json['settings']
4291              : array();
4292  
4293          foreach ( $metadata['selectors'] as $feature => $feature_selectors ) {
4294              /*
4295               * Skip if this is the block's root selector or the block doesn't
4296               * have any styles for the feature.
4297               */
4298              if ( 'root' === $feature || empty( $node[ $feature ] ) ) {
4299                  continue;
4300              }
4301  
4302              if ( is_array( $feature_selectors ) ) {
4303                  foreach ( $feature_selectors as $subfeature => $subfeature_selector ) {
4304                      if ( 'root' === $subfeature || empty( $node[ $feature ][ $subfeature ] ) ) {
4305                          continue;
4306                      }
4307  
4308                      /*
4309                       * Create temporary node containing only the subfeature data
4310                       * to leverage existing `compute_style_properties` function.
4311                       */
4312                      $subfeature_node = array(
4313                          $feature => array(
4314                              $subfeature => $node[ $feature ][ $subfeature ],
4315                          ),
4316                      );
4317  
4318                      // Generate style declarations.
4319                      $new_declarations = static::compute_style_properties( $subfeature_node, $settings, null, $this->theme_json );
4320  
4321                      // Merge subfeature declarations into feature declarations.
4322                      if ( isset( $declarations[ $subfeature_selector ] ) ) {
4323                          foreach ( $new_declarations as $new_declaration ) {
4324                              $declarations[ $subfeature_selector ][] = $new_declaration;
4325                          }
4326                      } else {
4327                          $declarations[ $subfeature_selector ] = $new_declarations;
4328                      }
4329  
4330                      /*
4331                       * Remove the subfeature from the block's node now its
4332                       * styles will be included under its own selector not the
4333                       * block's.
4334                       */
4335                      unset( $node[ $feature ][ $subfeature ] );
4336                  }
4337              }
4338  
4339              /*
4340               * Now subfeatures have been processed and removed we can process
4341               * feature root selector or simple string selector.
4342               */
4343              if (
4344                  is_string( $feature_selectors ) ||
4345                  ( isset( $feature_selectors['root'] ) && $feature_selectors['root'] )
4346              ) {
4347                  $feature_selector = is_string( $feature_selectors ) ? $feature_selectors : $feature_selectors['root'];
4348  
4349                  /*
4350                   * Create temporary node containing only the feature data
4351                   * to leverage existing `compute_style_properties` function.
4352                   */
4353                  $feature_node = array( $feature => $node[ $feature ] );
4354  
4355                  // Generate the style declarations.
4356                  $new_declarations = static::compute_style_properties( $feature_node, $settings, null, $this->theme_json );
4357  
4358                  /*
4359                   * Merge new declarations with any that already exist for
4360                   * the feature selector. This may occur when multiple block
4361                   * support features use the same custom selector.
4362                   */
4363                  if ( isset( $declarations[ $feature_selector ] ) ) {
4364                      foreach ( $new_declarations as $new_declaration ) {
4365                          $declarations[ $feature_selector ][] = $new_declaration;
4366                      }
4367                  } else {
4368                      $declarations[ $feature_selector ] = $new_declarations;
4369                  }
4370  
4371                  /*
4372                   * Remove the feature from the block's node now its styles
4373                   * will be included under its own selector not the block's.
4374                   */
4375                  unset( $node[ $feature ] );
4376              }
4377          }
4378  
4379          return $declarations;
4380      }
4381  
4382      /**
4383       * Replaces CSS variables with their values in place.
4384       *
4385       * @since 6.3.0
4386       * @since 6.5.0 Check for empty style before processing its value.
4387       *
4388       * @param array $styles CSS declarations to convert.
4389       * @param array $values key => value pairs to use for replacement.
4390       * @return array
4391       */
4392  	private static function convert_variables_to_value( $styles, $values ) {
4393          foreach ( $styles as $key => $style ) {
4394              if ( empty( $style ) ) {
4395                  continue;
4396              }
4397  
4398              if ( is_array( $style ) ) {
4399                  $styles[ $key ] = self::convert_variables_to_value( $style, $values );
4400                  continue;
4401              }
4402  
4403              if ( 0 <= strpos( $style, 'var(' ) ) {
4404                  // find all the variables in the string in the form of var(--variable-name, fallback), with fallback in the second capture group.
4405  
4406                  $has_matches = preg_match_all( '/var\(([^),]+)?,?\s?(\S+)?\)/', $style, $var_parts );
4407  
4408                  if ( $has_matches ) {
4409                      $resolved_style = $styles[ $key ];
4410                      foreach ( $var_parts[1] as $index => $var_part ) {
4411                          $key_in_values   = 'var(' . $var_part . ')';
4412                          $rule_to_replace = $var_parts[0][ $index ]; // the css rule to replace e.g. var(--wp--preset--color--vivid-green-cyan).
4413                          $fallback        = $var_parts[2][ $index ]; // the fallback value.
4414                          $resolved_style  = str_replace(
4415                              array(
4416                                  $rule_to_replace,
4417                                  $fallback,
4418                              ),
4419                              array(
4420                                  isset( $values[ $key_in_values ] ) ? $values[ $key_in_values ] : $rule_to_replace,
4421                                  isset( $values[ $fallback ] ) ? $values[ $fallback ] : $fallback,
4422                              ),
4423                              $resolved_style
4424                          );
4425                      }
4426                      $styles[ $key ] = $resolved_style;
4427                  }
4428              }
4429          }
4430  
4431          return $styles;
4432      }
4433  
4434      /**
4435       * Resolves the values of CSS variables in the given styles.
4436       *
4437       * @since 6.3.0
4438       * @param WP_Theme_JSON $theme_json The theme json resolver.
4439       *
4440       * @return WP_Theme_JSON The $theme_json with resolved variables.
4441       */
4442  	public static function resolve_variables( $theme_json ) {
4443          $settings    = $theme_json->get_settings();
4444          $styles      = $theme_json->get_raw_data()['styles'];
4445          $preset_vars = static::compute_preset_vars( $settings, static::VALID_ORIGINS );
4446          $theme_vars  = static::compute_theme_vars( $settings );
4447          $vars        = array_reduce(
4448              array_merge( $preset_vars, $theme_vars ),
4449              function ( $carry, $item ) {
4450                  $name                    = $item['name'];
4451                  $carry[ "var({$name})" ] = $item['value'];
4452                  return $carry;
4453              },
4454              array()
4455          );
4456  
4457          $theme_json->theme_json['styles'] = self::convert_variables_to_value( $styles, $vars );
4458          return $theme_json;
4459      }
4460  
4461      /**
4462       * Generates a selector for a block style variation.
4463       *
4464       * @since 6.5.0
4465       *
4466       * @param string $variation_name Name of the block style variation.
4467       * @param string $block_selector CSS selector for the block.
4468       * @return string Block selector with block style variation selector added to it.
4469       */
4470  	protected static function get_block_style_variation_selector( $variation_name, $block_selector ) {
4471          $variation_class = ".is-style-$variation_name";
4472  
4473          if ( ! $block_selector ) {
4474              return $variation_class;
4475          }
4476  
4477          $limit          = 1;
4478          $selector_parts = explode( ',', $block_selector );
4479          $result         = array();
4480  
4481          foreach ( $selector_parts as $part ) {
4482              $result[] = preg_replace_callback(
4483                  '/((?::\([^)]+\))?\s*)([^\s:]+)/',
4484                  function ( $matches ) use ( $variation_class ) {
4485                      return $matches[1] . $matches[2] . $variation_class;
4486                  },
4487                  $part,
4488                  $limit
4489              );
4490          }
4491  
4492          return implode( ',', $result );
4493      }
4494  
4495      /**
4496       * Collects valid block style variations keyed by block type.
4497       *
4498       * @since 6.6.0
4499       *
4500       * @return array Valid block style variations by block type.
4501       */
4502  	protected static function get_valid_block_style_variations() {
4503          $valid_variations = array();
4504          foreach ( self::get_blocks_metadata() as $block_name => $block_meta ) {
4505              if ( ! isset( $block_meta['styleVariations'] ) ) {
4506                  continue;
4507              }
4508              $valid_variations[ $block_name ] = array_keys( $block_meta['styleVariations'] );
4509          }
4510  
4511          return $valid_variations;
4512      }
4513  }


Generated : Sat Sep 14 08:20:02 2024 Cross-referenced by PHPXref