| 1 |
<?php |
| 2 |
namespace Elementor\Includes; |
| 3 |
|
| 4 |
class EditorAssetsAPI { |
| 5 |
protected array $config; |
| 6 |
|
| 7 |
const ASSETS_DATA_TRANSIENT_KEY = 'ASSETS_DATA_TRANSIENT_KEY'; |
| 8 |
|
| 9 |
const ASSETS_DATA_URL = 'ASSETS_DATA_URL'; |
| 10 |
|
| 11 |
const ASSETS_DATA_KEY = 'ASSETS_DATA_KEY'; |
| 12 |
|
| 13 |
public function __construct( array $config ) { |
| 14 |
$this->config = $config; |
| 15 |
} |
| 16 |
|
| 17 |
public function config( $key ): string { |
| 18 |
return $this->config[ $key ] ?? ''; |
| 19 |
} |
| 20 |
|
| 21 |
public function get_assets_data( $force_request = false ): array { |
| 22 |
$assets_data = $this->get_transient( $this->config( static::ASSETS_DATA_TRANSIENT_KEY ) ); |
| 23 |
|
| 24 |
if ( $force_request || false === $assets_data ) { |
| 25 |
$assets_data = $this->fetch_data(); |
| 26 |
$this->set_transient( $this->config( static::ASSETS_DATA_TRANSIENT_KEY ), $assets_data, '+1 hour' ); |
| 27 |
} |
| 28 |
|
| 29 |
return $assets_data; |
| 30 |
} |
| 31 |
|
| 32 |
private function fetch_data(): array { |
| 33 |
$response = wp_remote_get( $this->config( static::ASSETS_DATA_URL ) ); |
| 34 |
|
| 35 |
if ( is_wp_error( $response ) ) { |
| 36 |
return []; |
| 37 |
} |
| 38 |
|
| 39 |
$data = json_decode( wp_remote_retrieve_body( $response ), true ); |
| 40 |
|
| 41 |
if ( empty( $data[ $this->config( static::ASSETS_DATA_KEY ) ] ) || ! is_array( $data[ $this->config( static::ASSETS_DATA_KEY ) ] ) ) { |
| 42 |
return []; |
| 43 |
} |
| 44 |
|
| 45 |
return $data[ $this->config( static::ASSETS_DATA_KEY ) ]; |
| 46 |
} |
| 47 |
|
| 48 |
private function get_transient( $cache_key ) { |
| 49 |
$cache = get_option( $cache_key ); |
| 50 |
|
| 51 |
if ( empty( $cache['timeout'] ) ) { |
| 52 |
return false; |
| 53 |
} |
| 54 |
|
| 55 |
if ( current_time( 'timestamp' ) > $cache['timeout'] ) { |
| 56 |
return false; |
| 57 |
} |
| 58 |
|
| 59 |
return json_decode( $cache['value'], true ); |
| 60 |
} |
| 61 |
|
| 62 |
private function set_transient( $cache_key, $value, $expiration = '+12 hours' ): bool { |
| 63 |
$data = [ |
| 64 |
'timeout' => strtotime( $expiration, current_time( 'timestamp' ) ), |
| 65 |
'value' => wp_json_encode( $value ), |
| 66 |
]; |
| 67 |
|
| 68 |
return update_option( $cache_key, $data, false ); |
| 69 |
} |
| 70 |
} |
| 71 |
|