| 1 |
<?php |
| 2 |
|
| 3 |
namespace Elementor\Modules\Components\Utils; |
| 4 |
|
| 5 |
use Elementor\Modules\Components\PropTypes\Component_Instance_Prop_Type; |
| 6 |
|
| 7 |
if ( ! defined( 'ABSPATH' ) ) { |
| 8 |
exit; // Exit if accessed directly. |
| 9 |
} |
| 10 |
|
| 11 |
/** |
| 12 |
* Rewrites `component_id` inside every `e-component` widget in an elements tree |
| 13 |
* so it points at the component post recreated on the destination site instead |
| 14 |
* of the source-site post id that was serialized in the exported template. |
| 15 |
* |
| 16 |
* Used by both website-template (customization) and legacy kit import runners |
| 17 |
* before documents are saved. |
| 18 |
*/ |
| 19 |
class Remap_Component_Instance_Ids { |
| 20 |
public static function apply( array $elements, array $post_ids_map ): array { |
| 21 |
if ( empty( $post_ids_map ) ) { |
| 22 |
return $elements; |
| 23 |
} |
| 24 |
|
| 25 |
return array_map( |
| 26 |
function ( $element ) use ( $post_ids_map ) { |
| 27 |
return self::remap_element( $element, $post_ids_map ); |
| 28 |
}, |
| 29 |
$elements |
| 30 |
); |
| 31 |
} |
| 32 |
|
| 33 |
private static function remap_element( $element, array $post_ids_map ) { |
| 34 |
if ( ! is_array( $element ) ) { |
| 35 |
return $element; |
| 36 |
} |
| 37 |
|
| 38 |
if ( Component_Instance_Prop_Type::is_instance_element( $element ) ) { |
| 39 |
$element['settings'] = self::remap_component_id( $element['settings'] ?? [], $post_ids_map ); |
| 40 |
} |
| 41 |
|
| 42 |
if ( ! empty( $element['elements'] ) && is_array( $element['elements'] ) ) { |
| 43 |
$element['elements'] = self::apply( $element['elements'], $post_ids_map ); |
| 44 |
} |
| 45 |
|
| 46 |
return $element; |
| 47 |
} |
| 48 |
|
| 49 |
private static function remap_component_id( array $settings, array $post_ids_map ): array { |
| 50 |
$source_id = Component_Instance_Prop_Type::extract_component_id( $settings ); |
| 51 |
|
| 52 |
if ( ! is_numeric( $source_id ) || ! isset( $post_ids_map[ (int) $source_id ] ) ) { |
| 53 |
return $settings; |
| 54 |
} |
| 55 |
|
| 56 |
return Component_Instance_Prop_Type::set_component_id( $settings, (int) $post_ids_map[ (int) $source_id ] ); |
| 57 |
} |
| 58 |
} |
| 59 |
|