| 1 |
<?php |
| 2 |
|
| 3 |
namespace RadiusTheme\SB\Helpers; |
| 4 |
|
| 5 |
use RadiusTheme\SB\Traits\SingletonTrait; |
| 6 |
|
| 7 |
class ElementorDataMap { |
| 8 |
/** |
| 9 |
* Singleton |
| 10 |
*/ |
| 11 |
use SingletonTrait; |
| 12 |
|
| 13 |
/** |
| 14 |
* @var array |
| 15 |
*/ |
| 16 |
private static $cache = []; |
| 17 |
|
| 18 |
/*** |
| 19 |
* Elementor Data key |
| 20 |
*/ |
| 21 |
private const ELEMENTOR_DATA_KEY = '_elementor_data'; |
| 22 |
/*** |
| 23 |
* @var array |
| 24 |
*/ |
| 25 |
private array $eldata = []; |
| 26 |
|
| 27 |
/*** |
| 28 |
* @param int $post_id |
| 29 |
* |
| 30 |
* @return array|null |
| 31 |
*/ |
| 32 |
public function get_elementor_data( int $post_id ): ?array { |
| 33 |
$data = get_post_meta( $post_id, self::ELEMENTOR_DATA_KEY, true ); |
| 34 |
|
| 35 |
return json_decode( $data, true ); |
| 36 |
} |
| 37 |
|
| 38 |
/*** |
| 39 |
* @param string $widget_name |
| 40 |
* @param array|null $data |
| 41 |
* @param int|null $post_id |
| 42 |
* |
| 43 |
* @return array |
| 44 |
*/ |
| 45 |
public function get_widget_data( string $widget_name, ?array $data = null, ?int $post_id = null ): array { |
| 46 |
$cache_key = 'get_widget_data_' . $widget_name . '_' . $post_id; |
| 47 |
if ( isset( self::$cache[ $cache_key ] ) ) { |
| 48 |
return self::$cache[ $cache_key ]; |
| 49 |
} |
| 50 |
if ( ! $data && $post_id ) { |
| 51 |
$data = $this->get_elementor_data( $post_id ); |
| 52 |
} |
| 53 |
|
| 54 |
if ( empty( $data ) || ! is_array( $data ) ) { |
| 55 |
return []; |
| 56 |
} |
| 57 |
|
| 58 |
$this->search_el( $data, $widget_name ); |
| 59 |
self::$cache[ $cache_key ] = $this->eldata; |
| 60 |
return $this->eldata; |
| 61 |
} |
| 62 |
|
| 63 |
/*** |
| 64 |
* @param array $data |
| 65 |
* @param string $name |
| 66 |
* |
| 67 |
* @return void |
| 68 |
*/ |
| 69 |
private function search_el( array $data, string $name ): void { |
| 70 |
foreach ( $data as $value ) { |
| 71 |
if ( ! is_array( $value ) ) { |
| 72 |
continue; |
| 73 |
} |
| 74 |
|
| 75 |
if ( ! empty( $value['elements'] ) && is_array( $value['elements'] ) ) { |
| 76 |
$this->search_el( $value['elements'], $name ); |
| 77 |
} else { |
| 78 |
if ( $value['elType'] === 'widget' && $value['widgetType'] === $name ) { |
| 79 |
$this->eldata[] = $value; |
| 80 |
} |
| 81 |
} |
| 82 |
} |
| 83 |
} |
| 84 |
} |
| 85 |
|