Ignore:
Timestamp:
May 25, 2011 9:15:54 AM (13 years ago)
Author:
anonymous
Message:

Begin using PHP 5 class features ('public static...'); updated Currency.inc.php to support Xurrency's JSON API

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/lib/Currency.inc.php

    r376 r380  
    2727 *
    2828 * @author  Quinn Comendant <quinn@strangecode.com>
    29  * @version 1.0
     29 * @version 1.5
    3030 *
    3131 * Example of use:
    3232---------------------------------------------------------------------
    3333$currency = new Currency();
    34 echo $currency->getValue(1, 'eur', 'usd');
     34$currency->setParam(array('cache_dir' => COMMON_BASE . '/tmp/xcache'));
     35echo $currency->getRage('eur', 'usd');
     36echo $currency->getValue(125.50, 'eur', 'usd');
    3537---------------------------------------------------------------------
    3638 */
    37 
    38 require_once 'SOAP/Client.php';
    3939 
    4040class Currency {
     
    4444        'cache_result' => true,
    4545        'cache_dir' => '',
    46         'cache_age' => 28800, // 8 hours.
    47         'soap_api_url' => 'http://xurrency.com/servidor_soap.php',
     46        'cache_age' => 86400, // 24 hours.
     47        'api_type' => 'json', // 'json' or 'soap'.
     48        'api_url' => 'http://xurrency.com/api/%s/%s/%s',
     49        'api_key' => '',
    4850    );
    4951   
    50     // Object to hold SOAP_Client instance.
    51     var $_soap_client;
    52 
    5352    /**
    5453     * Cart constructor.
     
    5756    {
    5857        $app =& App::getInstance();
    59 
    60         // Initialize.
    61         if (!isset($_SESSION['_currency'])) {
    62             $_SESSION['_currency'] = array();
    63         }
    6458
    6559        // Set custom parameters.
     
    7973            }
    8074        }
    81        
    82         // Setup SOAP object.
    83         $this->_soap_client = new SOAP_Client($this->getParam('soap_api_url'));
    8475    }
    8576
     
    117108   
    118109    /*
    119     * Return the exchange value between the two given currencies.
     110    * Return the exchange value between the two given currencies for given amount.
    120111    *
    121112    * @access   public
    122     * @param    float   Base amount to convert from.
    123     * @param    string  3-letter currency code to convert from.
    124     * @param    string  3-letter currency code to convert to.
    125     * @return   mixed   Float exchange rate value, or false on error.
     113    * @param    float   $amount Base amount to convert from.
     114    * @param    string  $base   3-letter currency code to convert from.
     115    * @param    string  $target 3-letter currency code to convert to.
     116    * @return   mixed   Float converted currency value, or false on error.
    126117    * @author   Quinn Comendant <quinn@strangecode.com>
    127118    * @version  1.0
     
    130121    function getValue($amount, $base, $target)
    131122    {
     123        if (false !== $rate = $this->getRate($base, $target)) {
     124            return abs($rate * $amount);           
     125        } else {
     126            return false;
     127        }
     128    }
     129   
     130    /*
     131    * Return the currency conversion rate as a ratio.
     132    *
     133    * @access   public
     134    * @param    string  $base   3-letter currency code to convert from.
     135    * @param    string  $target 3-letter currency code to convert to.
     136    * @return   mixed   Float exchange rate value, or false on error.
     137    * @author   Quinn Comendant <quinn@strangecode.com>
     138    * @version  1.0
     139    * @since    25 May 2011 01:26:24
     140    */
     141    function getRate($base, $target)
     142    {
    132143        $app =& App::getInstance();
    133144
     
    136147        if (!$this->getParam('cache_result') || !$cache_file_mtime || $cache_file_mtime < time() - $this->getParam('cache_age')) {
    137148            // Get fresh data and create cached file if missing or expired.
    138             $app->logMsg(sprintf('Getting fresh currency exchange rates: %s-to-%s', $base, $target), LOG_DEBUG, __FILE__, __LINE__);
    139             $value = $this->_performAPICall('getValue', array(
    140                 'amount' => $amount,
     149            $app->logMsg(sprintf('Getting fresh currency exchange rate: %s-to-%s', $base, $target), LOG_DEBUG, __FILE__, __LINE__);
     150            $value = $this->_performAPICall(array(
     151                'amount' => '1',
    141152                'base' => $base,
    142153                'target' => $target
    143154            ));
    144155            if (false === $value || !is_numeric($value)) {
    145                 // Failed retrieving SOAP value. Use cached copy for now.
    146                 $app->logMsg(sprintf('Failed getting SOAP currency exchange rates: %s-to-%s, using cached copy', $base, $target), LOG_NOTICE, __FILE__, __LINE__);
     156                // Failed retrieving value. Use cached copy for now.
     157                $app->logMsg(sprintf('Failed getting currency exchange rate: %s-to-%s, using cached copy', $base, $target), LOG_NOTICE, __FILE__, __LINE__);
    147158                if (!$value = file_get_contents($cache_file_path)) {
    148                     $app->logMsg(sprintf('Failed reading target rate file: %s', $cache_file_path), LOG_ERR, __FILE__, __LINE__);
     159                    $app->logMsg(sprintf('Failed reading cached exchange rate file: %s', $cache_file_path), LOG_ERR, __FILE__, __LINE__);
    149160                    return false;
    150161                }
     
    154165            }
    155166        } else {
    156             $app->logMsg(sprintf('Getting cached currency exchange rates: %s-to-%s', $base, $target), LOG_DEBUG, __FILE__, __LINE__);
     167            $app->logMsg(sprintf('Getting cached currency exchange rate: %s-to-%s', $base, $target), LOG_DEBUG, __FILE__, __LINE__);
    157168            if (!$value = file_get_contents($cache_file_path)) {
    158169                $app->logMsg(sprintf('Failed reading target rate file: %s', $cache_file_path), LOG_ERR, __FILE__, __LINE__);
     
    160171            }
    161172        }
     173        $app->logMsg(sprintf('Found currency exchange rate: %s-to-%s = %s', $base, $target, $value), LOG_DEBUG, __FILE__, __LINE__);
    162174        return trim($value);
    163175    }
     
    169181     * @access private
    170182     */
    171     function _performAPICall($api_call, $parameters=null)
     183    function _performAPICall($parameters=null)
    172184    {
    173185        $app =& App::getInstance();
    174186       
    175         $result = $this->_soap_client->call($api_call, $parameters);
    176        
    177         if (PEAR::isError($result)) {
    178             $app->logMsg(sprintf('SOAP Pear error: %s', $result->getMessage()), LOG_WARNING, __FILE__, __LINE__);
    179             return false;
    180         }
    181 
    182         return $result;
     187        switch ($this->getParam('api_type')) {
     188        case 'json' :
     189            $api_url = $this->getParam('api_url');
     190            if ('' != $this->getParam('api_key')) {
     191                $api_url .= '?key=' . $this->getParam('api_key');
     192            }
     193            $json_response = file_get_contents(sprintf($api_url, $parameters['base'], $parameters['target'], $parameters['amount']));
     194            $json = json_decode($json_response);
     195            if (null === $json) {
     196                $app->logMsg(sprintf('Could not decode JSON response: %s', getDump($json_response)), LOG_WARNING, __FILE__, __LINE__);
     197                return false;
     198            } else if ($json->status === 'fail') {
     199                if ($json->code == 3) {
     200                    $app->logMsg(sprintf('Xurrency error LimitReachedException: %s', $json->message), LOG_WARNING, __FILE__, __LINE__);
     201                } elseif ($json->code == 2) {
     202                    $app->logMsg(sprintf('Xurrency error InvalidCurrencies: %s', $json->message), LOG_WARNING, __FILE__, __LINE__);
     203                } elseif ($json->code == 4 || $json->code == 5) {
     204                    $app->logMsg(sprintf('Xurrency error InvalidKey: %s', $json->message), LOG_WARNING, __FILE__, __LINE__);
     205                } else {
     206                    $app->logMsg(sprintf('Xurrency unknown error: %s', $json->message), LOG_WARNING, __FILE__, __LINE__);
     207                }
     208                return false;
     209            } else {
     210                return $json->result->value;
     211            }
     212            break;
     213
     214        case 'soap' :
     215            // Xurrency doesn't appear to support SOAP anymore, but we'll leave this here in case it comes back.
     216
     217            // Setup SOAP object.
     218            require_once 'SOAP/Client.php';
     219            $soap_client = new SOAP_Client($this->getParam('api_url'));
     220            // Call API
     221            $result = $soap_client->call('getValue', $parameters);
     222            // Check for errors.
     223            if (PEAR::isError($result)) {
     224                $app->logMsg(sprintf('SOAP Pear error: %s', $result->getMessage()), LOG_WARNING, __FILE__, __LINE__);
     225                return false;
     226            }
     227            return $result;
     228            break;
     229
     230        default :
     231            trigger_error('Unknown api_type: ' . $this->getParam('api_type'), E_USER_ERROR);
     232            die;
     233            break;
     234        }
    183235    }
    184236}
Note: See TracChangeset for help on using the changeset viewer.