Make WordPress Core


Ignore:
Timestamp:
01/19/2024 08:52:06 PM (17 months ago)
Author:
joemcgill
Message:

Editor: Support deferred block variation initialization on the server.

When registering blocks on the server using register_block_type() or similar functions, a set of block type variations can also be registered. However, in some cases building this variation data during block registration can be an expensive process, which is not needed in most contexts.

To address this problem, this adds support to the WP_Block_Type object for a new property, variation_callback, which can be used to register a callback for building variation data only when the block variations data is needed. The WP_Block_Type::variations property has been changed to a private property that is now accessed through the magic __get() method. The magic getter makes use of a new public method, WP_Block_Type::get_variations which will build variations from a registered callback if variations have not already been built.

Props spacedmonkey, thekt12, Mamaduka, gaambo, gziolo, mukesh27, joemcgill.
Fixes #59969.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/tests/rest-api/rest-block-type-controller.php

    r57068 r57315  
    736736
    737737    /**
     738     * @ticket 59969
     739     */
     740    public function test_variation_callback() {
     741        $block_type = 'test/block';
     742        $settings   = array(
     743            'title'              => true,
     744            'variation_callback' => array( $this, 'mock_variation_callback' ),
     745        );
     746        register_block_type( $block_type, $settings );
     747        wp_set_current_user( self::$admin_id );
     748        $request  = new WP_REST_Request( 'GET', '/wp/v2/block-types/' . $block_type );
     749        $response = rest_get_server()->dispatch( $request );
     750        $data     = $response->get_data();
     751        $this->assertSameSets( $this->mock_variation_callback(), $data['variations'] );
     752    }
     753
     754    /**
     755     * Mock variation callback.
     756     *
     757     * @return array
     758     */
     759    public function mock_variation_callback() {
     760        return array(
     761            array( 'name' => 'var1' ),
     762            array( 'name' => 'var2' ),
     763        );
     764    }
     765
     766    /**
    738767     * The create_item() method does not exist for block types.
    739768     *
Note: See TracChangeset for help on using the changeset viewer.