source: tags/2.1.5/lib/Currency.inc.php

Last change on this file was 377, checked in by quinn, 14 years ago

Releasing trunk as stable version 2.1.5

File size: 6.7 KB
Line 
1<?php
2/**
3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
5 * Copyright 2001-2010 Strangecode, LLC
6 *
7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/**
24 * Currency.inc.php
25 *
26 * Class to convert currency values.
27 *
28 * @author  Quinn Comendant <quinn@strangecode.com>
29 * @version 1.0
30 *
31 * Example of use:
32---------------------------------------------------------------------
33$currency = new Currency();
34echo $currency->getValue(1, 'eur', 'usd');
35---------------------------------------------------------------------
36 */
37
38require_once 'SOAP/Client.php';
39 
40class Currency {
41
42    // Configuration parameters for this object.
43    var $_params = array(
44        'cache_result' => true,
45        'cache_dir' => '',
46        'cache_age' => 28800, // 8 hours.
47        'soap_api_url' => 'http://xurrency.com/servidor_soap.php',
48    );
49   
50    // Object to hold SOAP_Client instance.
51    var $_soap_client;
52
53    /**
54     * Cart constructor.
55     */
56    function Currency($params=array())
57    {
58        $app =& App::getInstance();
59
60        // Initialize.
61        if (!isset($_SESSION['_currency'])) {
62            $_SESSION['_currency'] = array();
63        }
64
65        // Set custom parameters.
66        $this->setParam($params);
67       
68        // Setup cache directory.
69        if ($this->getParam('cache_result')) {
70            if ('' == $this->getParam('cache_dir')) {
71                // Use a sane default cache directory.
72                $this->setParam(array('cache_dir' => '/tmp/xcache_' . md5(COMMON_BASE)));
73            }
74            if (!is_dir($this->getParam('cache_dir'))) {
75                $app->logMsg(sprintf('Creating cache_dir: %s', $this->getParam('cache_dir')), LOG_INFO, __FILE__, __LINE__);               
76                if (!mkdir($this->getParam('cache_dir'))) {
77                    $app->logMsg(sprintf('Could not create cache_dir: %s', $this->getParam('cache_dir')), LOG_WARNING, __FILE__, __LINE__);               
78                }
79            }
80        }
81       
82        // Setup SOAP object.
83        $this->_soap_client = new SOAP_Client($this->getParam('soap_api_url'));
84    }
85
86    /**
87     * Set the params of this object.
88     *
89     * @param  array $params   Array of param keys and values to set.
90     */
91    function setParam($params=null)
92    {
93        if (isset($params) && is_array($params)) {
94            // Merge new parameters with old overriding only those passed.
95            $this->_params = array_merge($this->_params, $params);
96        }
97    }
98
99    /**
100     * Return the value of a parameter, if it exists.
101     *
102     * @access public
103     * @param string $param        Which parameter to return.
104     * @return mixed               Configured parameter value.
105     */
106    function getParam($param)
107    {
108        $app =& App::getInstance();
109   
110        if (isset($this->_params[$param])) {
111            return $this->_params[$param];
112        } else {
113            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
114            return null;
115        }
116    }
117   
118    /*
119    * Return the exchange value between the two given currencies.
120    *
121    * @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.
126    * @author   Quinn Comendant <quinn@strangecode.com>
127    * @version  1.0
128    * @since    05 May 2008 23:50:59
129    */
130    function getValue($amount, $base, $target)
131    {
132        $app =& App::getInstance();
133
134        $cache_file_path = sprintf('%s/%s-to-%s', $this->getParam('cache_dir'), $base, $target);
135        $cache_file_mtime = @filemtime($cache_file_path);
136        if (!$this->getParam('cache_result') || !$cache_file_mtime || $cache_file_mtime < time() - $this->getParam('cache_age')) {
137            // 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,
141                'base' => $base,
142                'target' => $target
143            ));
144            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__);
147                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__);
149                    return false;
150                }
151            } else if ($this->getParam('cache_result') && !filePutContents($cache_file_path, $value, LOCK_EX)) {
152                $app->logMsg(sprintf('Failed writing to target rate file: %s', $cache_file_path), LOG_ERR, __FILE__, __LINE__);
153                return false;
154            }
155        } else {
156            $app->logMsg(sprintf('Getting cached currency exchange rates: %s-to-%s', $base, $target), LOG_DEBUG, __FILE__, __LINE__);
157            if (!$value = file_get_contents($cache_file_path)) {
158                $app->logMsg(sprintf('Failed reading target rate file: %s', $cache_file_path), LOG_ERR, __FILE__, __LINE__);
159                return false;
160            }
161        }
162        return trim($value);
163    }
164   
165    /**
166     * @param  string
167     * @param  array
168     * @return mixed
169     * @access private
170     */
171    function _performAPICall($api_call, $parameters=null)
172    {
173        $app =& App::getInstance();
174       
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;
183    }
184}
185
186
187?>
Note: See TracBrowser for help on using the repository browser.