| 1 |
<?php |
| 2 |
|
| 3 |
namespace Yoast\WP\SEO\Helpers; |
| 4 |
|
| 5 |
use WP_Block_Parser_Block; |
| 6 |
|
| 7 |
/** |
| 8 |
* A helper object for blocks. |
| 9 |
*/ |
| 10 |
class Blocks_Helper { |
| 11 |
|
| 12 |
/** |
| 13 |
* Holds the Post_Helper instance. |
| 14 |
* |
| 15 |
* @var Post_Helper |
| 16 |
*/ |
| 17 |
private $post; |
| 18 |
|
| 19 |
/** |
| 20 |
* Constructs a Blocks_Helper instance. |
| 21 |
* |
| 22 |
* @codeCoverageIgnore It handles dependencies. |
| 23 |
* |
| 24 |
* @param Post_Helper $post The post helper. |
| 25 |
*/ |
| 26 |
public function __construct( Post_Helper $post ) { |
| 27 |
$this->post = $post; |
| 28 |
} |
| 29 |
|
| 30 |
/** |
| 31 |
* Returns all blocks in a given post. |
| 32 |
* |
| 33 |
* @param int $post_id The post id. |
| 34 |
* |
| 35 |
* @return array The blocks in a block-type => WP_Block_Parser_Block[] format. |
| 36 |
*/ |
| 37 |
public function get_all_blocks_from_post( $post_id ) { |
| 38 |
if ( ! $this->has_blocks_support() ) { |
| 39 |
return []; |
| 40 |
} |
| 41 |
|
| 42 |
$post = $this->post->get_post( $post_id ); |
| 43 |
return $this->get_all_blocks_from_content( $post->post_content ); |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* Returns all blocks in a given content. |
| 48 |
* |
| 49 |
* @param string $content The content. |
| 50 |
* |
| 51 |
* @return array The blocks in a block-type => WP_Block_Parser_Block[] format. |
| 52 |
*/ |
| 53 |
public function get_all_blocks_from_content( $content ) { |
| 54 |
if ( ! $this->has_blocks_support() ) { |
| 55 |
return []; |
| 56 |
} |
| 57 |
|
| 58 |
$collection = []; |
| 59 |
$blocks = \parse_blocks( $content ); |
| 60 |
return $this->collect_blocks( $blocks, $collection ); |
| 61 |
} |
| 62 |
|
| 63 |
/** |
| 64 |
* Checks if the installation has blocks support. |
| 65 |
* |
| 66 |
* @codeCoverageIgnore It only checks if a WordPress function exists. |
| 67 |
* |
| 68 |
* @return bool True when function parse_blocks exists. |
| 69 |
*/ |
| 70 |
protected function has_blocks_support() { |
| 71 |
return \function_exists( 'parse_blocks' ); |
| 72 |
} |
| 73 |
|
| 74 |
/** |
| 75 |
* Collects an array of blocks into an organised collection. |
| 76 |
* |
| 77 |
* @param WP_Block_Parser_Block[] $blocks The blocks. |
| 78 |
* @param array $collection The collection. |
| 79 |
* |
| 80 |
* @return array The blocks in a block-type => WP_Block_Parser_Block[] format. |
| 81 |
*/ |
| 82 |
private function collect_blocks( $blocks, $collection ) { |
| 83 |
foreach ( $blocks as $block ) { |
| 84 |
if ( ! isset( $collection[ $block['blockName'] ] ) || ! \is_array( $collection[ $block['blockName'] ] ) ) { |
| 85 |
$collection[ $block['blockName'] ] = []; |
| 86 |
} |
| 87 |
$collection[ $block['blockName'] ][] = $block; |
| 88 |
|
| 89 |
if ( isset( $block['innerBlocks'] ) ) { |
| 90 |
$collection = $this->collect_blocks( $block['innerBlocks'], $collection ); |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
return $collection; |
| 95 |
} |
| 96 |
} |
| 97 |
|