jetpack
/
vendor
/
wp-php-toolkit
/
data-liberation
/
DataFormatProducer
/
class-annotatedblockmarkupproducer.php
class-annotatedblockmarkupproducer.php
70 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WordPress\DataLiberation\DataFormatProducer; |
| 4 | |
| 5 | use WordPress\DataLiberation\DataFormatConsumer\BlocksWithMetadata; |
| 6 | use WP_HTML_Tag_Processor; |
| 7 | |
| 8 | /** |
| 9 | * Turns Block Markup + Metadata into a metadata-annotated Block Markup. |
| 10 | * |
| 11 | * Example: |
| 12 | * |
| 13 | * The following block markup: |
| 14 | * |
| 15 | * <!-- wp:paragraph --> |
| 16 | * <p>Hello <b>world</b>!</p> |
| 17 | * <!-- /wp:paragraph --> |
| 18 | * |
| 19 | * And metadata: |
| 20 | * |
| 21 | * array( |
| 22 | * 'post_title' => array( 'My first post' ), |
| 23 | * ) |
| 24 | * |
| 25 | * Becomes: |
| 26 | * |
| 27 | * <meta name="post_title" content="My first post"> |
| 28 | * <!-- wp:paragraph --> |
| 29 | * <p>Hello <b>world</b>!</p> |
| 30 | * <!-- /wp:paragraph --> |
| 31 | */ |
| 32 | class AnnotatedBlockMarkupProducer { |
| 33 | |
| 34 | /** |
| 35 | * @var BlocksWithMetadata |
| 36 | */ |
| 37 | private $blocks_with_meta; |
| 38 | |
| 39 | /** |
| 40 | * @var string |
| 41 | */ |
| 42 | private $result; |
| 43 | |
| 44 | public function __construct( BlocksWithMetadata $blocks_with_meta ) { |
| 45 | $this->blocks_with_meta = $blocks_with_meta; |
| 46 | } |
| 47 | |
| 48 | public function produce() { |
| 49 | if ( null === $this->result ) { |
| 50 | $this->result = ''; |
| 51 | foreach ( $this->blocks_with_meta->get_all_metadata() as $key => $values ) { |
| 52 | foreach ( $values as $value ) { |
| 53 | $p = new WP_HTML_Tag_Processor( '<meta>' ); |
| 54 | $p->next_tag(); |
| 55 | $p->set_attribute( 'name', $key ); |
| 56 | if ( is_array( $value ) || is_object( $value ) ) { |
| 57 | $value = json_encode( $value ); |
| 58 | } |
| 59 | $p->set_attribute( 'content', $value ); |
| 60 | $p->set_attribute( 'type', gettype( $value ) ); |
| 61 | $this->result .= $p->get_updated_html() . "\n"; |
| 62 | } |
| 63 | } |
| 64 | $this->result .= "\n" . trim( $this->blocks_with_meta->get_block_markup(), "\n" ); |
| 65 | } |
| 66 | |
| 67 | return $this->result; |
| 68 | } |
| 69 | } |
| 70 |