| 1 |
<?php |
| 2 |
namespace Crocoblock\Blocks_Style\Migrator; |
| 3 |
|
| 4 |
class Post_Handler { |
| 5 |
|
| 6 |
private $post_id; |
| 7 |
private $data; |
| 8 |
private $normalizer; |
| 9 |
|
| 10 |
/** |
| 11 |
* Migrator_Post_Handler constructor. |
| 12 |
* |
| 13 |
* @param int $post_id Post ID. |
| 14 |
* @param string $meta_value Meta value to migrate. |
| 15 |
*/ |
| 16 |
public function __construct( int $post_id, string $json_data ) { |
| 17 |
$this->post_id = $post_id; |
| 18 |
$this->data = json_decode( $json_data, true ); |
| 19 |
$this->normalizer = new Data_Normalizer(); |
| 20 |
} |
| 21 |
|
| 22 |
/** |
| 23 |
* Migrate data. |
| 24 |
* |
| 25 |
* return bool |
| 26 |
*/ |
| 27 |
public function migrate_data() { |
| 28 |
|
| 29 |
if ( ! $this->post_id || ! $this->data ) { |
| 30 |
return false; |
| 31 |
} |
| 32 |
|
| 33 |
foreach ( $this->data as $block_id => $block_controls ) { |
| 34 |
$new_data = $this->normalizer->normalize( $block_controls ); |
| 35 |
$post_blocks[ $block_id ] = $new_data; |
| 36 |
} |
| 37 |
|
| 38 |
$post = get_post( $this->post_id ); |
| 39 |
|
| 40 |
if ( ! $post ) { |
| 41 |
return false; |
| 42 |
} |
| 43 |
|
| 44 |
$post_content = $post->post_content; |
| 45 |
|
| 46 |
foreach ( $post_blocks as $block_id => $controls ) { |
| 47 |
$controls_json = $this->controls_json( $controls ); |
| 48 |
$block_id_pattern = '"blockID":"' . $block_id . '"'; |
| 49 |
|
| 50 |
// Add new controls only if they are not already present. |
| 51 |
if ( false === strpos( $post_content, $block_id_pattern . ',"crocoblock_styles"' ) ) { |
| 52 |
$post_content = str_replace( |
| 53 |
$block_id_pattern, |
| 54 |
$block_id_pattern . ',' . $controls_json, |
| 55 |
$post_content |
| 56 |
); |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
$post_content = wp_slash( $post_content ); |
| 61 |
|
| 62 |
// Update post content with new controls. |
| 63 |
wp_update_post( [ |
| 64 |
'ID' => $this->post_id, |
| 65 |
'post_content' => $post_content, |
| 66 |
] ); |
| 67 |
|
| 68 |
return true; |
| 69 |
} |
| 70 |
|
| 71 |
/** |
| 72 |
* Convert controls to JSON. |
| 73 |
* |
| 74 |
* @param array $controls Controls to convert. |
| 75 |
* |
| 76 |
* @return string JSON encoded controls. |
| 77 |
*/ |
| 78 |
private function controls_json( array $controls ): string { |
| 79 |
$controls['_uniqueClassName'] = substr( uniqid('cb-'), 0, 11 ); |
| 80 |
return '"crocoblock_styles":' . json_encode( $controls, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); |
| 81 |
} |
| 82 |
} |