source: trunk/lib/Currency.inc.php @ 334

Last change on this file since 334 was 334, checked in by quinn, 16 years ago

Fixed lots of misplings. I'm so embarrassed! ;P

File size: 5.9 KB
Line 
1<?php
2/**
3 * Currency.inc.php
4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
5 *
6 * Class to convert currency values.
7 *
8 * @author  Quinn Comendant <quinn@strangecode.com>
9 * @version 1.0
10 *
11 * Example of use:
12---------------------------------------------------------------------
13$currency = new Currency();
14echo $currency->getValue(1, 'eur', 'usd');
15---------------------------------------------------------------------
16 */
17
18require_once 'SOAP/Client.php';
19 
20class Currency {
21
22    // Configuration parameters for this object.
23    var $_params = array(
24        'cache_result' => true,
25        'cache_dir' => '',
26        'cache_age' => 28800, // 8 hours.
27        'soap_api_url' => 'http://xurrency.com/servidor_soap.php',
28    );
29   
30    // Object to hold SOAP_Client instance.
31    var $_soap_client;
32
33    /**
34     * Cart constructor.
35     */
36    function Currency($params=array())
37    {
38        $app =& App::getInstance();
39
40        // Initialize.
41        if (!isset($_SESSION['_currency'])) {
42            $_SESSION['_currency'] = array();
43        }
44
45        // Set custom parameters.
46        $this->setParam($params);
47       
48        // Setup cache directory.
49        if ($this->getParam('cache_result')) {
50            if ('' == $this->getParam('cache_dir')) {
51                // Use a sane default cache directory.
52                $this->setParam(array('cache_dir' => '/tmp/xcache_' . md5(COMMON_BASE)));
53            }
54            if (!is_dir($this->getParam('cache_dir'))) {
55                $app->logMsg(sprintf('Creating cache_dir: %s', $this->getParam('cache_dir')), LOG_INFO, __FILE__, __LINE__);               
56                if (!mkdir($this->getParam('cache_dir'))) {
57                    $app->logMsg(sprintf('Could not create cache_dir: %s', $this->getParam('cache_dir')), LOG_WARNING, __FILE__, __LINE__);               
58                }
59            }
60        }
61       
62        // Setup SOAP object.
63        $this->_soap_client = new SOAP_Client($this->getParam('soap_api_url'));
64    }
65
66    /**
67     * Set the params of this object.
68     *
69     * @param  array $params   Array of param keys and values to set.
70     */
71    function setParam($params=null)
72    {
73        if (isset($params) && is_array($params)) {
74            // Merge new parameters with old overriding only those passed.
75            $this->_params = array_merge($this->_params, $params);
76        }
77    }
78
79    /**
80     * Return the value of a parameter, if it exists.
81     *
82     * @access public
83     * @param string $param        Which parameter to return.
84     * @return mixed               Configured parameter value.
85     */
86    function getParam($param)
87    {
88        $app =& App::getInstance();
89   
90        if (isset($this->_params[$param])) {
91            return $this->_params[$param];
92        } else {
93            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
94            return null;
95        }
96    }
97   
98    /*
99    * Return the exchange value between the two given currencies.
100    *
101    * @access   public
102    * @param    float   Base amount to convert from.
103    * @param    string  3-letter currency code to convert from.
104    * @param    string  3-letter currency code to convert to.
105    * @return   mixed   Float exchange rate value, or false on error.
106    * @author   Quinn Comendant <quinn@strangecode.com>
107    * @version  1.0
108    * @since    05 May 2008 23:50:59
109    */
110    function getValue($amount, $base, $target)
111    {
112        $app =& App::getInstance();
113
114        $cache_file_path = sprintf('%s/%s-to-%s', $this->getParam('cache_dir'), $base, $target);
115        $cache_file_mtime = @filemtime($cache_file_path);
116        if (!$this->getParam('cache_result') || !$cache_file_mtime || $cache_file_mtime < time() - $this->getParam('cache_age')) {
117            // Get fresh data and create cached file if missing or expired.
118            $app->logMsg(sprintf('Getting fresh currency exchange rates: %s-to-%s', $base, $target), LOG_DEBUG, __FILE__, __LINE__);
119            $value = $this->_performAPICall('getValue', array(
120                'amount' => $amount,
121                'base' => $base,
122                'target' => $target
123            ));
124            if (false === $value || !is_numeric($value)) {
125                // Failed retrieving SOAP value. Use cached copy for now.
126                $app->logMsg(sprintf('Failed getting SOAP currency exchange rates: %s-to-%s, using cached copy', $base, $target), LOG_NOTICE, __FILE__, __LINE__);
127                if (!$value = file_get_contents($cache_file_path)) {
128                    $app->logMsg(sprintf('Failed reading target rate file: %s', $cache_file_path), LOG_ERR, __FILE__, __LINE__);
129                    return false;
130                }
131            } else if ($this->getParam('cache_result') && !filePutContents($cache_file_path, $value, LOCK_EX)) {
132                $app->logMsg(sprintf('Failed writing to target rate file: %s', $cache_file_path), LOG_ERR, __FILE__, __LINE__);
133                return false;
134            }
135        } else {
136            $app->logMsg(sprintf('Getting cached currency exchange rates: %s-to-%s', $base, $target), LOG_DEBUG, __FILE__, __LINE__);
137            if (!$value = file_get_contents($cache_file_path)) {
138                $app->logMsg(sprintf('Failed reading target rate file: %s', $cache_file_path), LOG_ERR, __FILE__, __LINE__);
139                return false;
140            }
141        }
142        return trim($value);
143    }
144   
145    /**
146     * @param  string
147     * @param  array
148     * @return mixed
149     * @access private
150     */
151    function _performAPICall($api_call, $parameters=null)
152    {
153        $app =& App::getInstance();
154       
155        $result = $this->_soap_client->call($api_call, $parameters);
156       
157        if (PEAR::isError($result)) {
158            $app->logMsg(sprintf('SOAP Pear error: %s', $result->getMessage()), LOG_WARNING, __FILE__, __LINE__);
159            return false;
160        }
161
162        return $result;
163    }
164}
165
166
167?>
Note: See TracBrowser for help on using the repository browser.