1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
<?php
namespace SIW\External;
class Exchange_Rates{
const API_URL = 'http://data.fixer.io/api/latest';
protected $api_key;
protected $transient_name = 'siw_exchange_rates';
public function __construct() {
$this->api_key = siw_get_option( 'exchange_rates_api_key' );
if ( empty( $this->api_key ) ) {
return;
}
}
public function get_rates() {
$exchange_rates = get_transient( $this->transient_name );
if ( false === $exchange_rates ) {
$exchange_rates = $this->retrieve_rates();
if ( false == $exchange_rates ) {
return false;
}
set_transient( $this->transient_name, $exchange_rates, DAY_IN_SECONDS );
}
return $exchange_rates;
}
protected function retrieve_rates() {
$url = add_query_arg( [
'access_key' => $this->api_key,
], self::API_URL );
$args = [
'timeout' => 10,
'redirection' => 0,
];
$response = wp_safe_remote_get( $url, $args );
if ( false === $this->check_response( $response ) ) {
return false;
}
$body = json_decode( wp_remote_retrieve_body( $response ), true );
if ( false == $body['success'] ) {
return false;
}
$exchange_rates = [];
foreach ( $body['rates'] as $currency => $rate ) {
$exchange_rates[ $currency ] = 1 / $rate;
}
return $exchange_rates;
}
protected function check_response( $response ) {
if ( is_wp_error( $response ) ) {
return false;
}
$statuscode = wp_remote_retrieve_response_code( $response );
if ( \WP_Http::OK != $statuscode ) {
return false;
}
return true;
}
}