jetpack
/
vendor
/
wp-php-toolkit
/
data-liberation
/
DataFormatConsumer
/
class-annotatedblockmarkupconsumer.php
class-annotatedblockmarkupconsumer.php
6 days ago
class-blockswithmetadata.php
6 days ago
class-markupprocessorconsumer.php
6 days ago
interface-data-format-consumer.php
6 days ago
class-annotatedblockmarkupconsumer.php
68 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WordPress\DataLiberation\DataFormatConsumer; |
| 4 | |
| 5 | use WP_HTML_Processor; |
| 6 | |
| 7 | /** |
| 8 | * Converts a metadata-annotated block markup into block markup+metadata pair. |
| 9 | * |
| 10 | * Example: |
| 11 | * |
| 12 | * <meta name="post_title" content="My first post"> |
| 13 | * <!-- wp:paragraph {"className":"my-class"} --> |
| 14 | * <p class="my-class">Hello world!</p> |
| 15 | * <!-- /wp:paragraph --> |
| 16 | * |
| 17 | * Becomes: |
| 18 | * |
| 19 | * <!-- wp:paragraph --> |
| 20 | * <p>Hello <b>world</b>!</p> |
| 21 | * <!-- /wp:paragraph --> |
| 22 | * |
| 23 | * With the following metadata: |
| 24 | * |
| 25 | * array( |
| 26 | * 'post_title' => array( 'My first post' ), |
| 27 | * ) |
| 28 | */ |
| 29 | class AnnotatedBlockMarkupConsumer implements DataFormatConsumer { |
| 30 | |
| 31 | /** |
| 32 | * @var string |
| 33 | */ |
| 34 | private $original_html; |
| 35 | |
| 36 | /** |
| 37 | * @var ConsumedBlockMarkup |
| 38 | */ |
| 39 | private $result; |
| 40 | |
| 41 | public function __construct( $original_html ) { |
| 42 | $this->original_html = $original_html; |
| 43 | } |
| 44 | |
| 45 | public function consume() { |
| 46 | if ( ! $this->result ) { |
| 47 | $block_markup = ''; |
| 48 | $metadata = array(); |
| 49 | foreach ( parse_blocks( $this->original_html ) as $block ) { |
| 50 | if ( null === $block['blockName'] ) { |
| 51 | $html_converter = new MarkupProcessorConsumer( WP_HTML_Processor::create_fragment( $block['innerHTML'] ) ); |
| 52 | $result = $html_converter->consume(); |
| 53 | $block_markup .= $result->get_block_markup() . "\n"; |
| 54 | $metadata = array_merge( $metadata, $result->get_all_metadata() ); |
| 55 | } else { |
| 56 | $block_markup .= serialize_block( $block ) . "\n"; |
| 57 | } |
| 58 | } |
| 59 | $this->result = new BlocksWithMetadata( |
| 60 | $block_markup, |
| 61 | $metadata |
| 62 | ); |
| 63 | } |
| 64 | |
| 65 | return $this->result; |
| 66 | } |
| 67 | } |
| 68 |