From 2c04bdef4e5f56631d9b446da46878e280e9d24e Mon Sep 17 00:00:00 2001 From: Luis Felipe Zaguini <26530524+zaguiini@users.noreply.github.com> Date: Tue, 3 Sep 2024 20:07:54 -0300 Subject: [PATCH] Safely parse fields from JSON (#111) --- includes/runtime/class-content-model.php | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/includes/runtime/class-content-model.php b/includes/runtime/class-content-model.php index 6dcbe53..938bc7f 100644 --- a/includes/runtime/class-content-model.php +++ b/includes/runtime/class-content-model.php @@ -79,7 +79,7 @@ public function __construct( WP_Post $content_model_post ) { // TODO: Not load this eagerly. $this->blocks = $this->inflate_template_blocks( $this->template ); - $this->fields = json_decode( get_post_meta( $content_model_post->ID, 'fields', true ), true ); + $this->fields = $this->parse_fields(); $this->register_meta_fields(); add_action( 'enqueue_block_editor_assets', array( $this, 'maybe_enqueue_templating_scripts' ) ); @@ -160,6 +160,27 @@ private function register_post_type() { ); } + /** + * Parses the fields associated with the Content Model. + * + * @return array Fields associated with the Content Model. + */ + private function parse_fields() { + $fields = get_post_meta( $this->post_id, 'fields', true ); + + if ( ! $fields ) { + return array(); + } + + $decoded_files = json_decode( $fields, true ); + + if ( is_array( $decoded_files ) ) { + return $decoded_files; + } + + return array(); + } + /** * Recursively inflates (i.e., maps the block into Content_Model_Block) the blocks.