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


Generated : Wed Jul 9 08:20:01 2025 Cross-referenced by PHPXref