class-wc-blocks-utils.php
85 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Blocks Utils |
| 4 | * |
| 5 | * Used by core components that need to work with blocks. |
| 6 | * |
| 7 | * @package WooCommerce\Blocks\Utils |
| 8 | * @version 5.0.0 |
| 9 | */ |
| 10 | |
| 11 | defined( 'ABSPATH' ) || exit; |
| 12 | |
| 13 | /** |
| 14 | * Blocks Utility class. |
| 15 | */ |
| 16 | class WC_Blocks_Utils { |
| 17 | |
| 18 | /** |
| 19 | * Get blocks from a woocommerce page. |
| 20 | * |
| 21 | * @param string $woo_page_name A woocommerce page e.g. `checkout` or `cart`. |
| 22 | * @return array Array of blocks as returned by parse_blocks(). |
| 23 | */ |
| 24 | private static function get_all_blocks_from_page( $woo_page_name ) { |
| 25 | $page_id = wc_get_page_id( $woo_page_name ); |
| 26 | |
| 27 | $page = get_post( $page_id ); |
| 28 | if ( ! $page ) { |
| 29 | return array(); |
| 30 | } |
| 31 | |
| 32 | $blocks = parse_blocks( $page->post_content ); |
| 33 | if ( ! $blocks ) { |
| 34 | return array(); |
| 35 | } |
| 36 | |
| 37 | return $blocks; |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Get all instances of the specified block on a specific woo page |
| 42 | * (e.g. `cart` or `checkout` page). |
| 43 | * |
| 44 | * @param string $block_name The name (id) of a block, e.g. `woocommerce/cart`. |
| 45 | * @param string $woo_page_name The woo page to search, e.g. `cart`. |
| 46 | * @return array Array of blocks as returned by parse_blocks(). |
| 47 | */ |
| 48 | public static function get_blocks_from_page( $block_name, $woo_page_name ) { |
| 49 | $page_blocks = self::get_all_blocks_from_page( $woo_page_name ); |
| 50 | |
| 51 | // Get any instances of the specified block. |
| 52 | return array_values( |
| 53 | array_filter( |
| 54 | $page_blocks, |
| 55 | function ( $block ) use ( $block_name ) { |
| 56 | return ( $block_name === $block['blockName'] ); |
| 57 | } |
| 58 | ) |
| 59 | ); |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Check if a given page contains a particular block. |
| 64 | * |
| 65 | * @param int|WP_Post $page Page post ID or post object. |
| 66 | * @param string $block_name The name (id) of a block, e.g. `woocommerce/cart`. |
| 67 | * @return bool Boolean value if the page contains the block or not. Null in case the page does not exist. |
| 68 | */ |
| 69 | public static function has_block_in_page( $page, $block_name ) { |
| 70 | $page_to_check = get_post( $page ); |
| 71 | if ( null === $page_to_check ) { |
| 72 | return false; |
| 73 | } |
| 74 | |
| 75 | $blocks = parse_blocks( $page_to_check->post_content ); |
| 76 | foreach ( $blocks as $block ) { |
| 77 | if ( $block_name === $block['blockName'] ) { |
| 78 | return true; |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | return false; |
| 83 | } |
| 84 | } |
| 85 |