move logic to utils file

This commit is contained in:
Luigi 2022-04-27 12:01:02 +02:00
parent 650fe593a1
commit 98a91cd132
2 changed files with 47 additions and 15 deletions

View File

@ -70,9 +70,11 @@ class WC_Blocks_Utils {
$template = get_block_template( get_stylesheet() . '//' . $template_part_slug, 'wp_template_part' );
$blocks = parse_blocks( $template->content );
$flatten_blocks = self::flatten_blocks( $blocks );
return array_values(
array_filter(
$blocks,
$flatten_blocks,
function ( $block ) use ( $block_name ) {
return ( $block_name === $block['blockName'] );
}
@ -102,4 +104,47 @@ class WC_Blocks_Utils {
return false;
}
/**
* Return blocks with their inner blocks flattened.
*
* @param array $blocks Array of blocks as returned by parse_blocks().
* @return array All blocks.
*/
public static function flatten_blocks( $blocks ) {
return array_reduce(
$blocks,
function( $carry, $block ) {
array_push( $carry, array_diff_key( $block, array_flip( array( 'innerBlocks' ) ) ) );
if ( isset( $block['innerBlocks'] ) ) {
$inner_blocks = self::flatten_blocks( $block['innerBlocks'] );
return array_merge( $carry, $inner_blocks );
}
return $carry;
},
array()
);
}
/**
* Get all instances of the specified block from the widget area.
*
* @param array $block_name The name (id) of a block, e.g. `woocommerce/mini-cart`.
* @return array Array of blocks as returned by parse_blocks().
*/
public static function get_blocks_from_widget_area( $block_name ) {
return array_reduce(
get_option( 'widget_block' ),
function ( $acc, $block ) use ( $block_name ) {
$parsed_blocks = ! empty( $block ) && is_array( $block ) ? parse_blocks( $block['content'] ) : array();
if ( ! empty( $parsed_blocks ) && $block_name === $parsed_blocks[0]['blockName'] ) {
array_push( $acc, $parsed_blocks[0] );
return $acc;
}
return $acc;
},
array()
);
}
}

View File

@ -786,20 +786,7 @@ class WC_Tracker {
*/
public static function get_mini_cart_info() {
$mini_cart_block_name = 'woocommerce/mini-cart';
$mini_cart_block_data = wc_current_theme_is_fse_theme() ? WC_Blocks_Utils::get_block_from_template_part( $mini_cart_block_name, 'header' ) :
array_reduce(
get_option( 'widget_block' ),
function ( $acc, $block ) use ( $mini_cart_block_name ) {
$parsed_blocks = ! empty( $block ) && is_array( $block ) ? parse_blocks( $block['content'] ) : array();
if ( ! empty( $parsed_blocks ) && $mini_cart_block_name === $parsed_blocks[0]['blockName'] ) {
array_push( $acc, $parsed_blocks[0] );
return $acc;
}
return $acc;
},
array()
);
$mini_cart_block_data = wc_current_theme_is_fse_theme() ? WC_Blocks_Utils::get_block_from_template_part( $mini_cart_block_name, 'header' ) : WC_Blocks_Utils::get_blocks_from_widget_area( $mini_cart_block_name );
return array(
'mini_cart_used' => empty( $mini_cart_block_data[0] ) ? 'No' : 'Yes',
'mini_cart_block_attributes' => empty( $mini_cart_block_data[0] ) ? array() : $mini_cart_block_data[0]['attrs'],