[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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


Generated : Thu Oct 30 08:20:06 2025 Cross-referenced by PHPXref