From 6f0a3faf7165016ca7aa9b4613971c1029cdaf9b Mon Sep 17 00:00:00 2001 From: Alex Kazhukhouski Date: Fri, 24 Jan 2025 17:55:44 +0100 Subject: [PATCH] Provides object typing on the fly functionality for the attributes of type object with typing provided in default. --- includes/Blocks/Block.php | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/includes/Blocks/Block.php b/includes/Blocks/Block.php index 3b470dd6..f42131bb 100644 --- a/includes/Blocks/Block.php +++ b/includes/Blocks/Block.php @@ -153,11 +153,13 @@ private function get_attribute_type( $name, $attribute, $prefix ) { $type = 'Int'; break; case 'array': + // Process attributes query. if ( isset( $attribute['query'] ) ) { $type = [ 'list_of' => $this->create_and_register_inner_object_type( $name, $attribute['query'], $prefix ) ]; break; } + // Process scalar array or list of items. $of_type = null; if ( isset( $attribute['items'] ) ) { $of_type = $this->get_attribute_type( $name, $attribute['items'], $prefix ); @@ -166,7 +168,13 @@ private function get_attribute_type( $name, $attribute, $prefix ) { $type = null !== $of_type ? [ 'list_of' => $of_type ] : Scalar::ATTRIBUTES_ARRAY_TYPE_NAME; break; case 'object': - $type = Scalar::ATTRIBUTES_OBJECT_TYPE_NAME; + // Proceed with the typed object if typing provided, otherwise continue with scalar object. + $typed = []; + if ( ! empty( $attribute['default']['__typed'] ) ) { + $typed = $this->build_typed_object_config( $attribute['default'] ); + } + + $type = $typed ? $this->create_and_register_inner_object_type( $name, $typed, $prefix ) : Scalar::ATTRIBUTES_OBJECT_TYPE_NAME; break; } @@ -241,6 +249,28 @@ private function create_and_register_inner_object_type( string $name, array $con return $type; } + /** + * Verifies if the default record has a typed object configuration for the object type and generates config for it. + * + * @param array $default_attribute Default record of the attribute. + */ + private function build_typed_object_config( $default_attribute ): array { + if ( ! is_array( $default_attribute['__typed'] ) ) { + return []; + } + + return array_combine( + array_keys( $default_attribute['__typed'] ), + array_map( + static fn ( $key ) => [ + 'type' => $default_attribute['__typed'][ $key ], + 'default' => $default_attribute[ $key ] ?? null, + ], + array_keys( $default_attribute['__typed'] ) + ) + ) ?: []; + } + /** * Creates the new attribute fields for inner block types. *