WCML_Exchange_Rates_YahooFinance

The WooCommerce Multilingual WCML Exchange Rates YahooFinance class.

Defined (1)

The class is defined in the following location(s).

/inc/currencies/exchange-rate-services/class-wcml-exchange-rates-yahoo-finance.php  
  1. class WCML_Exchange_Rates_YahooFinance extends WCML_Exchange_Rate_Service{ 
  2.  
  3. private $id = 'yahoo'; 
  4. private $name = 'Yahoo! Finance'; 
  5. private $url = 'https://finance.yahoo.com/currency-converter'; 
  6. private $api_url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=%s'; // EURUSD=X, GBPUSD=X 
  7.  
  8. protected $api_key = ''; 
  9. const REQUIRES_KEY = false; 
  10.  
  11. function __construct() { 
  12. parent::__construct( $this->id, $this->name, $this->api_url, $this->url ); 
  13.  
  14. /** 
  15. * @param $from string 
  16. * @param $to array 
  17. * @return array 
  18. * @throws Exception 
  19. */ 
  20. public function get_rates( $from, $tos ) { 
  21.  
  22. parent::clear_last_error(); 
  23. $rates = array(); 
  24.  
  25. $pairs = array(); 
  26. foreach( $tos as $to ) { 
  27. $pairs[] = $from . $to . '=X'; 
  28.  
  29. $url = sprintf( $this->api_url, join(', ', $pairs) ); 
  30.  
  31. $http = new WP_Http(); 
  32. $data = $http->request( $url ); 
  33.  
  34. if( is_wp_error( $data ) ) { 
  35.  
  36. $http_error = join("\n", $data->get_error_messages() ); 
  37. parent::save_last_error( $http_error ); 
  38. throw new Exception( $http_error ); 
  39.  
  40. } else { 
  41.  
  42. // str_getcsv not working as expected 
  43. $lines = explode("\n", trim( $data['body'] ) ); 
  44. foreach( $lines as $k => $line ) { 
  45.  
  46. // Exception: sometimes it returns N/A 
  47. if( substr( $line, 0, 3) === 'N/A' ) { 
  48. $values = array_values( $tos ); 
  49. $to = $values[$k]; 
  50. $rate = trim( substr( $line, 4 ) ); 
  51. }else{ 
  52. $to = substr( $line, 1, 3); 
  53. $rate = trim( substr( $line, 6 ) ); 
  54.  
  55. if( !is_numeric( $rate ) ) { 
  56. $error = sprintf( __("Error reading the exchange rate for %s. Please try again. If the error persist, try selecting a different exchange rate service.", 'woocommerce-multilingual' ), $to ); 
  57. parent::save_last_error( $error ); 
  58. throw new Exception( $error ); 
  59.  
  60. $rates[$to] = $rate; 
  61.  
  62.  
  63. return $rates; 
  64.  
  65.