Last active
September 17, 2023 02:06
-
-
Save dlh01/b5aa636c167772046efea93898ba450a to your computer and use it in GitHub Desktop.
Decorator pattern for serializing blocks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// https://github.com/WordPress/wordpress-develop/pull/5187 | |
namespace GH5187; | |
interface Block_Content { | |
public function content( string $content, array $block ): string; | |
} | |
final class Serialized_Blocks { | |
public function __construct( | |
private readonly array $blocks, | |
private Block_Content $content, | |
) {} | |
public function serialized(): string { | |
$result = ''; | |
foreach ( $this->blocks as $block ) { | |
$result .= $this->block( $block ); | |
}; | |
return $result; | |
} | |
private function block( $block ): string { | |
if ( ! is_array( $block['attrs'] ) ) { | |
$block['attrs'] = array(); | |
} | |
$block_content = ''; | |
$index = 0; | |
foreach ( $block['innerContent'] as $chunk ) { | |
$block_content .= is_string( $chunk ) ? $chunk : $this->block( $block['innerBlocks'][ $index++ ] ); | |
} | |
return $this->content->content( $block_content, $block ); | |
} | |
} | |
class Callback implements Block_Content { | |
public function __construct( | |
private $callback, | |
private Block_Content $origin, | |
) {} | |
public function content( string $content, array $block ): string { | |
$block = call_user_func( $this->callback, $block ); | |
return $this->origin->content( $content, $block ); | |
} | |
} | |
class Delimited implements Block_Content { | |
public function content( string $content, array $block ): string { | |
return get_comment_delimited_block_content( | |
$block['blockName'], | |
$block['attrs'], | |
$content, | |
); | |
} | |
} | |
/* | |
$blocks = [...]; | |
$content. = new Serialized_Blocks( $blocks, new Delimited() ); | |
$serialized = $content->serialized(); | |
$fn = fn ( array $block ) => ...; | |
$content = new Serialized_Blocks( $blocks, new Callback( $fn, new Delimited() ) ); | |
$serialized = new $content->serialized(); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment