&$class_item ) { if ( empty( $class_item['variants'] ) || ! is_array( $class_item['variants'] ) ) { continue; } foreach ( $class_item['variants'] as &$variant ) { if ( empty( $variant['props'] ) || ! is_array( $variant['props'] ) ) { continue; } $variant['props'] = self::rewrite_variable_refs_recursive( $variant['props'], $id_map, $variable_types ); } } return $snapshot; } private static function rewrite_variable_refs_recursive( array $data, array $id_map, array $variable_types ): array { foreach ( $data as $key => $value ) { if ( ! is_array( $value ) ) { continue; } $type = $value['$$type'] ?? null; $val = $value['value'] ?? null; if ( $type && in_array( $type, $variable_types, true ) && is_string( $val ) && isset( $id_map[ $val ] ) ) { $data[ $key ]['value'] = $id_map[ $val ]; continue; } $data[ $key ] = self::rewrite_variable_refs_recursive( $value, $id_map, $variable_types ); } return $data; } public static function flatten_variables_in_classes_snapshot( array $classes_snapshot, array $variables_snapshot, ?array $only_ids = null ): array { if ( empty( $classes_snapshot['items'] ) ) { return $classes_snapshot; } $variable_data = $variables_snapshot['data'] ?? []; $variable_types = Variable_Type_Keys::get_all(); $type_map = Variable_Type_Keys::get_type_mappings(); $ids_to_flatten = null !== $only_ids ? array_fill_keys( $only_ids, true ) : null; foreach ( $classes_snapshot['items'] as $class_id => &$class_item ) { if ( empty( $class_item['variants'] ) || ! is_array( $class_item['variants'] ) ) { continue; } foreach ( $class_item['variants'] as &$variant ) { if ( empty( $variant['props'] ) || ! is_array( $variant['props'] ) ) { continue; } $variant['props'] = self::flatten_variable_refs_in_props( $variant['props'], $variable_data, $variable_types, $type_map, $ids_to_flatten ); } } return $classes_snapshot; } private static function flatten_variable_refs_in_props( array $data, array $variable_data, array $variable_types, array $type_map, ?array $ids_to_flatten = null ): array { foreach ( $data as $key => $value ) { if ( ! is_array( $value ) ) { continue; } $type = $value['$$type'] ?? null; $var_id = $value['value'] ?? null; if ( $type && in_array( $type, $variable_types, true ) && is_string( $var_id ) && isset( $variable_data[ $var_id ] ) ) { if ( null !== $ids_to_flatten && ! isset( $ids_to_flatten[ $var_id ] ) ) { continue; } $resolved_type = $type_map[ $type ] ?? null; $resolved_value = $variable_data[ $var_id ]['value'] ?? null; if ( $resolved_type && null !== $resolved_value ) { $data[ $key ] = [ '$$type' => $resolved_type, 'value' => Variable_Type_Keys::convert_value_for_resolved_type( $resolved_type, $resolved_value ), ]; } continue; } $data[ $key ] = self::flatten_variable_refs_in_props( $value, $variable_data, $variable_types, $type_map, $ids_to_flatten ); } return $data; } }