[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp-block.php (source)

   1  <?php
   2  /**
   3   * Blocks API: WP_Block class
   4   *
   5   * @package WordPress
   6   * @since 5.5.0
   7   */
   8  
   9  /**
  10   * Class representing a parsed instance of a block.
  11   *
  12   * @since 5.5.0
  13   * @property array $attributes
  14   */
  15  #[AllowDynamicProperties]
  16  class WP_Block {
  17  
  18      /**
  19       * Original parsed array representation of block.
  20       *
  21       * @since 5.5.0
  22       * @var array
  23       */
  24      public $parsed_block;
  25  
  26      /**
  27       * Name of block.
  28       *
  29       * @example "core/paragraph"
  30       *
  31       * @since 5.5.0
  32       * @var string
  33       */
  34      public $name;
  35  
  36      /**
  37       * Block type associated with the instance.
  38       *
  39       * @since 5.5.0
  40       * @var WP_Block_Type
  41       */
  42      public $block_type;
  43  
  44      /**
  45       * Block context values.
  46       *
  47       * @since 5.5.0
  48       * @var array
  49       */
  50      public $context = array();
  51  
  52      /**
  53       * All available context of the current hierarchy.
  54       *
  55       * @since 5.5.0
  56       * @var array
  57       * @access protected
  58       */
  59      protected $available_context;
  60  
  61      /**
  62       * Block type registry.
  63       *
  64       * @since 5.9.0
  65       * @var WP_Block_Type_Registry
  66       * @access protected
  67       */
  68      protected $registry;
  69  
  70      /**
  71       * List of inner blocks (of this same class)
  72       *
  73       * @since 5.5.0
  74       * @var WP_Block_List
  75       */
  76      public $inner_blocks = array();
  77  
  78      /**
  79       * Resultant HTML from inside block comment delimiters after removing inner
  80       * blocks.
  81       *
  82       * @example "...Just <!-- wp:test /--> testing..." -> "Just testing..."
  83       *
  84       * @since 5.5.0
  85       * @var string
  86       */
  87      public $inner_html = '';
  88  
  89      /**
  90       * List of string fragments and null markers where inner blocks were found
  91       *
  92       * @example array(
  93       *   'inner_html'    => 'BeforeInnerAfter',
  94       *   'inner_blocks'  => array( block, block ),
  95       *   'inner_content' => array( 'Before', null, 'Inner', null, 'After' ),
  96       * )
  97       *
  98       * @since 5.5.0
  99       * @var array
 100       */
 101      public $inner_content = array();
 102  
 103      /**
 104       * Constructor.
 105       *
 106       * Populates object properties from the provided block instance argument.
 107       *
 108       * The given array of context values will not necessarily be available on
 109       * the instance itself, but is treated as the full set of values provided by
 110       * the block's ancestry. This is assigned to the private `available_context`
 111       * property. Only values which are configured to consumed by the block via
 112       * its registered type will be assigned to the block's `context` property.
 113       *
 114       * @since 5.5.0
 115       *
 116       * @param array                  $block             Array of parsed block properties.
 117       * @param array                  $available_context Optional array of ancestry context values.
 118       * @param WP_Block_Type_Registry $registry          Optional block type registry.
 119       */
 120  	public function __construct( $block, $available_context = array(), $registry = null ) {
 121          $this->parsed_block = $block;
 122          $this->name         = $block['blockName'];
 123  
 124          if ( is_null( $registry ) ) {
 125              $registry = WP_Block_Type_Registry::get_instance();
 126          }
 127  
 128          $this->registry = $registry;
 129  
 130          $this->block_type = $registry->get_registered( $this->name );
 131  
 132          $this->available_context = $available_context;
 133  
 134          if ( ! empty( $this->block_type->uses_context ) ) {
 135              foreach ( $this->block_type->uses_context as $context_name ) {
 136                  if ( array_key_exists( $context_name, $this->available_context ) ) {
 137                      $this->context[ $context_name ] = $this->available_context[ $context_name ];
 138                  }
 139              }
 140          }
 141  
 142          if ( ! empty( $block['innerBlocks'] ) ) {
 143              $child_context = $this->available_context;
 144  
 145              if ( ! empty( $this->block_type->provides_context ) ) {
 146                  foreach ( $this->block_type->provides_context as $context_name => $attribute_name ) {
 147                      if ( array_key_exists( $attribute_name, $this->attributes ) ) {
 148                          $child_context[ $context_name ] = $this->attributes[ $attribute_name ];
 149                      }
 150                  }
 151              }
 152  
 153              $this->inner_blocks = new WP_Block_List( $block['innerBlocks'], $child_context, $registry );
 154          }
 155  
 156          if ( ! empty( $block['innerHTML'] ) ) {
 157              $this->inner_html = $block['innerHTML'];
 158          }
 159  
 160          if ( ! empty( $block['innerContent'] ) ) {
 161              $this->inner_content = $block['innerContent'];
 162          }
 163      }
 164  
 165      /**
 166       * Returns a value from an inaccessible property.
 167       *
 168       * This is used to lazily initialize the `attributes` property of a block,
 169       * such that it is only prepared with default attributes at the time that
 170       * the property is accessed. For all other inaccessible properties, a `null`
 171       * value is returned.
 172       *
 173       * @since 5.5.0
 174       *
 175       * @param string $name Property name.
 176       * @return array|null Prepared attributes, or null.
 177       */
 178  	public function __get( $name ) {
 179          if ( 'attributes' === $name ) {
 180              $this->attributes = isset( $this->parsed_block['attrs'] ) ?
 181                  $this->parsed_block['attrs'] :
 182                  array();
 183  
 184              if ( ! is_null( $this->block_type ) ) {
 185                  $this->attributes = $this->block_type->prepare_attributes_for_render( $this->attributes );
 186              }
 187  
 188              return $this->attributes;
 189          }
 190  
 191          return null;
 192      }
 193  
 194      /**
 195       * Processes the block bindings and updates the block attributes with the values from the sources.
 196       *
 197       * A block might contain bindings in its attributes. Bindings are mappings
 198       * between an attribute of the block and a source. A "source" is a function
 199       * registered with `register_block_bindings_source()` that defines how to
 200       * retrieve a value from outside the block, e.g. from post meta.
 201       *
 202       * This function will process those bindings and update the block's attributes
 203       * with the values coming from the bindings.
 204       *
 205       * ### Example
 206       *
 207       * The "bindings" property for an Image block might look like this:
 208       *
 209       * ```json
 210       * {
 211       *   "metadata": {
 212       *     "bindings": {
 213       *       "title": {
 214       *         "source": "core/post-meta",
 215       *         "args": { "key": "text_custom_field" }
 216       *       },
 217       *       "url": {
 218       *         "source": "core/post-meta",
 219       *         "args": { "key": "url_custom_field" }
 220       *       }
 221       *     }
 222       *   }
 223       * }
 224       * ```
 225       *
 226       * The above example will replace the `title` and `url` attributes of the Image
 227       * block with the values of the `text_custom_field` and `url_custom_field` post meta.
 228       *
 229       * @since 6.5.0
 230       *
 231       * @return array The computed block attributes for the provided block bindings.
 232       */
 233  	private function process_block_bindings() {
 234          $parsed_block               = $this->parsed_block;
 235          $computed_attributes        = array();
 236          $supported_block_attributes = array(
 237              'core/paragraph' => array( 'content' ),
 238              'core/heading'   => array( 'content' ),
 239              'core/image'     => array( 'id', 'url', 'title', 'alt' ),
 240              'core/button'    => array( 'url', 'text', 'linkTarget', 'rel' ),
 241          );
 242  
 243          // If the block doesn't have the bindings property, isn't one of the supported
 244          // block types, or the bindings property is not an array, return the block content.
 245          if (
 246              ! isset( $supported_block_attributes[ $this->name ] ) ||
 247              empty( $parsed_block['attrs']['metadata']['bindings'] ) ||
 248              ! is_array( $parsed_block['attrs']['metadata']['bindings'] )
 249          ) {
 250              return $computed_attributes;
 251          }
 252  
 253          foreach ( $parsed_block['attrs']['metadata']['bindings'] as $attribute_name => $block_binding ) {
 254              // If the attribute is not in the supported list, process next attribute.
 255              if ( ! in_array( $attribute_name, $supported_block_attributes[ $this->name ], true ) ) {
 256                  continue;
 257              }
 258              // If no source is provided, or that source is not registered, process next attribute.
 259              if ( ! isset( $block_binding['source'] ) || ! is_string( $block_binding['source'] ) ) {
 260                  continue;
 261              }
 262  
 263              $block_binding_source = get_block_bindings_source( $block_binding['source'] );
 264              if ( null === $block_binding_source ) {
 265                  continue;
 266              }
 267  
 268              $source_args  = ! empty( $block_binding['args'] ) && is_array( $block_binding['args'] ) ? $block_binding['args'] : array();
 269              $source_value = $block_binding_source->get_value( $source_args, $this, $attribute_name );
 270  
 271              // If the value is not null, process the HTML based on the block and the attribute.
 272              if ( ! is_null( $source_value ) ) {
 273                  $computed_attributes[ $attribute_name ] = $source_value;
 274              }
 275          }
 276  
 277          return $computed_attributes;
 278      }
 279  
 280      /**
 281       * Depending on the block attribute name, replace its value in the HTML based on the value provided.
 282       *
 283       * @since 6.5.0
 284       *
 285       * @param string $block_content  Block content.
 286       * @param string $attribute_name The attribute name to replace.
 287       * @param mixed  $source_value   The value used to replace in the HTML.
 288       * @return string The modified block content.
 289       */
 290  	private function replace_html( string $block_content, string $attribute_name, $source_value ) {
 291          $block_type = $this->block_type;
 292          if ( ! isset( $block_type->attributes[ $attribute_name ]['source'] ) ) {
 293              return $block_content;
 294          }
 295  
 296          // Depending on the attribute source, the processing will be different.
 297          switch ( $block_type->attributes[ $attribute_name ]['source'] ) {
 298              case 'html':
 299              case 'rich-text':
 300                  $block_reader = new WP_HTML_Tag_Processor( $block_content );
 301  
 302                  // TODO: Support for CSS selectors whenever they are ready in the HTML API.
 303                  // In the meantime, support comma-separated selectors by exploding them into an array.
 304                  $selectors = explode( ',', $block_type->attributes[ $attribute_name ]['selector'] );
 305                  // Add a bookmark to the first tag to be able to iterate over the selectors.
 306                  $block_reader->next_tag();
 307                  $block_reader->set_bookmark( 'iterate-selectors' );
 308  
 309                  // TODO: This shouldn't be needed when the `set_inner_html` function is ready.
 310                  // Store the parent tag and its attributes to be able to restore them later in the button.
 311                  // The button block has a wrapper while the paragraph and heading blocks don't.
 312                  if ( 'core/button' === $this->name ) {
 313                      $button_wrapper                 = $block_reader->get_tag();
 314                      $button_wrapper_attribute_names = $block_reader->get_attribute_names_with_prefix( '' );
 315                      $button_wrapper_attrs           = array();
 316                      foreach ( $button_wrapper_attribute_names as $name ) {
 317                          $button_wrapper_attrs[ $name ] = $block_reader->get_attribute( $name );
 318                      }
 319                  }
 320  
 321                  foreach ( $selectors as $selector ) {
 322                      // If the parent tag, or any of its children, matches the selector, replace the HTML.
 323                      if ( strcasecmp( $block_reader->get_tag( $selector ), $selector ) === 0 || $block_reader->next_tag(
 324                          array(
 325                              'tag_name' => $selector,
 326                          )
 327                      ) ) {
 328                          $block_reader->release_bookmark( 'iterate-selectors' );
 329  
 330                          // TODO: Use `set_inner_html` method whenever it's ready in the HTML API.
 331                          // Until then, it is hardcoded for the paragraph, heading, and button blocks.
 332                          // Store the tag and its attributes to be able to restore them later.
 333                          $selector_attribute_names = $block_reader->get_attribute_names_with_prefix( '' );
 334                          $selector_attrs           = array();
 335                          foreach ( $selector_attribute_names as $name ) {
 336                              $selector_attrs[ $name ] = $block_reader->get_attribute( $name );
 337                          }
 338                          $selector_markup = "<$selector>" . wp_kses_post( $source_value ) . "</$selector>";
 339                          $amended_content = new WP_HTML_Tag_Processor( $selector_markup );
 340                          $amended_content->next_tag();
 341                          foreach ( $selector_attrs as $attribute_key => $attribute_value ) {
 342                              $amended_content->set_attribute( $attribute_key, $attribute_value );
 343                          }
 344                          if ( 'core/paragraph' === $this->name || 'core/heading' === $this->name ) {
 345                              return $amended_content->get_updated_html();
 346                          }
 347                          if ( 'core/button' === $this->name ) {
 348                              $button_markup  = "<$button_wrapper>{$amended_content->get_updated_html()}</$button_wrapper>";
 349                              $amended_button = new WP_HTML_Tag_Processor( $button_markup );
 350                              $amended_button->next_tag();
 351                              foreach ( $button_wrapper_attrs as $attribute_key => $attribute_value ) {
 352                                  $amended_button->set_attribute( $attribute_key, $attribute_value );
 353                              }
 354                              return $amended_button->get_updated_html();
 355                          }
 356                      } else {
 357                          $block_reader->seek( 'iterate-selectors' );
 358                      }
 359                  }
 360                  $block_reader->release_bookmark( 'iterate-selectors' );
 361                  return $block_content;
 362  
 363              case 'attribute':
 364                  $amended_content = new WP_HTML_Tag_Processor( $block_content );
 365                  if ( ! $amended_content->next_tag(
 366                      array(
 367                          // TODO: build the query from CSS selector.
 368                          'tag_name' => $block_type->attributes[ $attribute_name ]['selector'],
 369                      )
 370                  ) ) {
 371                      return $block_content;
 372                  }
 373                  $amended_content->set_attribute( $block_type->attributes[ $attribute_name ]['attribute'], $source_value );
 374                  return $amended_content->get_updated_html();
 375                  break;
 376  
 377              default:
 378                  return $block_content;
 379                  break;
 380          }
 381          return;
 382      }
 383  
 384  
 385      /**
 386       * Generates the render output for the block.
 387       *
 388       * @since 5.5.0
 389       * @since 6.5.0 Added block bindings processing.
 390       *
 391       * @global WP_Post $post Global post object.
 392       *
 393       * @param array $options {
 394       *     Optional options object.
 395       *
 396       *     @type bool $dynamic Defaults to 'true'. Optionally set to false to avoid using the block's render_callback.
 397       * }
 398       * @return string Rendered block output.
 399       */
 400  	public function render( $options = array() ) {
 401          global $post;
 402          $options = wp_parse_args(
 403              $options,
 404              array(
 405                  'dynamic' => true,
 406              )
 407          );
 408  
 409          // Process the block bindings and get attributes updated with the values from the sources.
 410          $computed_attributes = $this->process_block_bindings();
 411          if ( ! empty( $computed_attributes ) ) {
 412              // Merge the computed attributes with the original attributes.
 413              $this->attributes = array_merge( $this->attributes, $computed_attributes );
 414          }
 415  
 416          $is_dynamic    = $options['dynamic'] && $this->name && null !== $this->block_type && $this->block_type->is_dynamic();
 417          $block_content = '';
 418  
 419          if ( ! $options['dynamic'] || empty( $this->block_type->skip_inner_blocks ) ) {
 420              $index = 0;
 421  
 422              foreach ( $this->inner_content as $chunk ) {
 423                  if ( is_string( $chunk ) ) {
 424                      $block_content .= $chunk;
 425                  } else {
 426                      $inner_block  = $this->inner_blocks[ $index ];
 427                      $parent_block = $this;
 428  
 429                      /** This filter is documented in wp-includes/blocks.php */
 430                      $pre_render = apply_filters( 'pre_render_block', null, $inner_block->parsed_block, $parent_block );
 431  
 432                      if ( ! is_null( $pre_render ) ) {
 433                          $block_content .= $pre_render;
 434                      } else {
 435                          $source_block = $inner_block->parsed_block;
 436  
 437                          /** This filter is documented in wp-includes/blocks.php */
 438                          $inner_block->parsed_block = apply_filters( 'render_block_data', $inner_block->parsed_block, $source_block, $parent_block );
 439  
 440                          /** This filter is documented in wp-includes/blocks.php */
 441                          $inner_block->context = apply_filters( 'render_block_context', $inner_block->context, $inner_block->parsed_block, $parent_block );
 442  
 443                          $block_content .= $inner_block->render();
 444                      }
 445  
 446                      ++$index;
 447                  }
 448              }
 449          }
 450  
 451          if ( ! empty( $computed_attributes ) && ! empty( $block_content ) ) {
 452              foreach ( $computed_attributes as $attribute_name => $source_value ) {
 453                  $block_content = $this->replace_html( $block_content, $attribute_name, $source_value );
 454              }
 455          }
 456  
 457          if ( $is_dynamic ) {
 458              $global_post = $post;
 459              $parent      = WP_Block_Supports::$block_to_render;
 460  
 461              WP_Block_Supports::$block_to_render = $this->parsed_block;
 462  
 463              $block_content = (string) call_user_func( $this->block_type->render_callback, $this->attributes, $block_content, $this );
 464  
 465              WP_Block_Supports::$block_to_render = $parent;
 466  
 467              $post = $global_post;
 468          }
 469  
 470          if ( ( ! empty( $this->block_type->script_handles ) ) ) {
 471              foreach ( $this->block_type->script_handles as $script_handle ) {
 472                  wp_enqueue_script( $script_handle );
 473              }
 474          }
 475  
 476          if ( ! empty( $this->block_type->view_script_handles ) ) {
 477              foreach ( $this->block_type->view_script_handles as $view_script_handle ) {
 478                  wp_enqueue_script( $view_script_handle );
 479              }
 480          }
 481  
 482          if ( ! empty( $this->block_type->view_script_module_ids ) ) {
 483              foreach ( $this->block_type->view_script_module_ids as $view_script_module_id ) {
 484                  wp_enqueue_script_module( $view_script_module_id );
 485              }
 486          }
 487  
 488          if ( ( ! empty( $this->block_type->style_handles ) ) ) {
 489              foreach ( $this->block_type->style_handles as $style_handle ) {
 490                  wp_enqueue_style( $style_handle );
 491              }
 492          }
 493  
 494          if ( ( ! empty( $this->block_type->view_style_handles ) ) ) {
 495              foreach ( $this->block_type->view_style_handles as $view_style_handle ) {
 496                  wp_enqueue_style( $view_style_handle );
 497              }
 498          }
 499  
 500          /**
 501           * Filters the content of a single block.
 502           *
 503           * @since 5.0.0
 504           * @since 5.9.0 The `$instance` parameter was added.
 505           *
 506           * @param string   $block_content The block content.
 507           * @param array    $block         The full block, including name and attributes.
 508           * @param WP_Block $instance      The block instance.
 509           */
 510          $block_content = apply_filters( 'render_block', $block_content, $this->parsed_block, $this );
 511  
 512          /**
 513           * Filters the content of a single block.
 514           *
 515           * The dynamic portion of the hook name, `$name`, refers to
 516           * the block name, e.g. "core/paragraph".
 517           *
 518           * @since 5.7.0
 519           * @since 5.9.0 The `$instance` parameter was added.
 520           *
 521           * @param string   $block_content The block content.
 522           * @param array    $block         The full block, including name and attributes.
 523           * @param WP_Block $instance      The block instance.
 524           */
 525          $block_content = apply_filters( "render_block_{$this->name}", $block_content, $this->parsed_block, $this );
 526  
 527          return $block_content;
 528      }
 529  }


Generated : Thu Apr 18 08:20:02 2024 Cross-referenced by PHPXref