2
0

Currency.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Currency
  17. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id$
  20. */
  21. /**
  22. * include needed classes
  23. */
  24. require_once 'Zend/Locale.php';
  25. require_once 'Zend/Locale/Data.php';
  26. require_once 'Zend/Locale/Format.php';
  27. /**
  28. * Class for handling currency notations
  29. *
  30. * @category Zend
  31. * @package Zend_Currency
  32. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  33. * @license http://framework.zend.com/license/new-bsd New BSD License
  34. */
  35. class Zend_Currency
  36. {
  37. // Constants for defining what currency symbol should be displayed
  38. const NO_SYMBOL = 1;
  39. const USE_SYMBOL = 2;
  40. const USE_SHORTNAME = 3;
  41. const USE_NAME = 4;
  42. // Constants for defining the position of the currencysign
  43. const STANDARD = 8;
  44. const RIGHT = 16;
  45. const LEFT = 32;
  46. /**
  47. * Locale for this currency
  48. *
  49. * @var string
  50. */
  51. private $_locale = null;
  52. /**
  53. * Options array
  54. *
  55. * The following options are available
  56. * 'position' => Position for the currency sign
  57. * 'script' => Script for the output
  58. * 'format' => Locale for numeric output
  59. * 'display' => Currency detail to show
  60. * 'precision' => Precision for the currency
  61. * 'name' => Name for this currency
  62. * 'currency' => 3 lettered international abbreviation
  63. * 'symbol' => Currency symbol
  64. *
  65. * @var array
  66. * @see Zend_Locale
  67. */
  68. protected $_options = array(
  69. 'position' => self::STANDARD,
  70. 'script' => null,
  71. 'format' => null,
  72. 'display' => self::NO_SYMBOL,
  73. 'precision' => 2,
  74. 'name' => null,
  75. 'currency' => null,
  76. 'symbol' => null
  77. );
  78. /**
  79. * Creates a currency instance. Every supressed parameter is used from the actual or the given locale.
  80. *
  81. * @param string $currency OPTIONAL currency short name
  82. * @param string|Zend_Locale $locale OPTIONAL locale name
  83. * @throws Zend_Currency_Exception When currency is invalid
  84. */
  85. public function __construct($currency = null, $locale = null)
  86. {
  87. if (Zend_Locale::isLocale($currency, true, false)) {
  88. $temp = $locale;
  89. $locale = $currency;
  90. $currency = $temp;
  91. }
  92. $this->setLocale($locale);
  93. // Get currency details
  94. $this->_options['currency'] = self::getShortName($currency, $this->_locale);
  95. $this->_options['name'] = self::getName($currency, $this->_locale);
  96. $this->_options['symbol'] = self::getSymbol($currency, $this->_locale);
  97. if (($this->_options['currency'] === null) and ($this->_options['name'] === null)) {
  98. require_once 'Zend/Currency/Exception.php';
  99. throw new Zend_Currency_Exception("Currency '$currency' not found");
  100. }
  101. // Get the format
  102. $this->_options['display'] = self::NO_SYMBOL;
  103. if (empty($this->_options['symbol']) === false) {
  104. $this->_options['display'] = self::USE_SYMBOL;
  105. } else if (empty($this->_options['currency']) === false) {
  106. $this->_options['display'] = self::USE_SHORTNAME;
  107. }
  108. }
  109. /**
  110. * Returns a localized currency string
  111. *
  112. * @param integer|float $value Currency value
  113. * @param array $options OPTIONAL options to set temporary
  114. * @throws Zend_Currency_Exception When the value is not a number
  115. * @return string
  116. */
  117. public function toCurrency($value, array $options = array())
  118. {
  119. // Validate the passed number
  120. if ((isset($value) === false) or (is_numeric($value) === false)) {
  121. require_once 'Zend/Currency/Exception.php';
  122. throw new Zend_Currency_Exception("Value '$value' has to be numeric");
  123. }
  124. $options = $this->_checkOptions($options) + $this->_options;
  125. // Format the number
  126. $format = $options['format'];
  127. $locale = $this->_locale;
  128. if (empty($format)) {
  129. $format = Zend_Locale_Data::getContent($this->_locale, 'currencynumber');
  130. } else if (Zend_Locale::isLocale($format, true, false)) {
  131. $locale = $format;
  132. $format = Zend_Locale_Data::getContent($format, 'currencynumber');
  133. }
  134. $symbols = Zend_Locale_Data::getList($locale, 'symbols');
  135. $original = $value;
  136. $value = Zend_Locale_Format::toNumber($value, array('locale' => $locale,
  137. 'number_format' => $format,
  138. 'precision' => $options['precision']));
  139. if ($options['position'] !== self::STANDARD) {
  140. $value = str_replace('¤', '', $value);
  141. $space = '';
  142. if (iconv_strpos($value, ' ') !== false) {
  143. $value = str_replace(' ', '', $value);
  144. $space = ' ';
  145. }
  146. if ($options['position'] == self::LEFT) {
  147. $value = '¤' . $space . $value;
  148. } else {
  149. $value = $value . $space . '¤';
  150. }
  151. }
  152. // Localize the number digits
  153. if (empty($options['script']) === false) {
  154. $value = Zend_Locale_Format::convertNumerals($value, 'Latn', $options['script']);
  155. }
  156. // Get the sign to be placed next to the number
  157. if (is_numeric($options['display']) === false) {
  158. $sign = $options['display'];
  159. } else {
  160. switch($options['display']) {
  161. case self::USE_SYMBOL:
  162. $sign = $this->_extractPattern($options['symbol'], $original);
  163. break;
  164. case self::USE_SHORTNAME:
  165. $sign = $options['currency'];
  166. break;
  167. case self::USE_NAME:
  168. $sign = $options['name'];
  169. break;
  170. default:
  171. $sign = '';
  172. $value = str_replace(' ', '', $value);
  173. break;
  174. }
  175. }
  176. $value = str_replace('¤', $sign, $value);
  177. return $value;
  178. }
  179. /**
  180. * Internal method to extract the currency pattern
  181. * when a choice is given based on the given value
  182. *
  183. * @param string $pattern
  184. * @param float|integer $value
  185. * @return string
  186. */
  187. private function _extractPattern($pattern, $value)
  188. {
  189. if (strpos($pattern, '|') === false) {
  190. return $pattern;
  191. }
  192. $patterns = explode('|', $pattern);
  193. $token = $pattern;
  194. $value = trim(str_replace('¤', '', $value));
  195. krsort($patterns);
  196. foreach($patterns as $content) {
  197. if (strpos($content, '<') !== false) {
  198. $check = iconv_substr($content, 0, iconv_strpos($content, '<'));
  199. $token = iconv_substr($content, iconv_strpos($content, '<') + 1);
  200. if ($check < $value) {
  201. return $token;
  202. }
  203. } else {
  204. $check = iconv_substr($content, 0, iconv_strpos($content, '≤'));
  205. $token = iconv_substr($content, iconv_strpos($content, '≤') + 1);
  206. if ($check <= $value) {
  207. return $token;
  208. }
  209. }
  210. }
  211. return $token;
  212. }
  213. /**
  214. * Sets the formating options of the localized currency string
  215. * If no parameter is passed, the standard setting of the
  216. * actual set locale will be used
  217. *
  218. * @param array $options (Optional) Options to set
  219. * @return Zend_Currency
  220. */
  221. public function setFormat(array $options = array())
  222. {
  223. $this->_options = $this->_checkOptions($options) + $this->_options;
  224. return $this;
  225. }
  226. /**
  227. * Internal function for checking static given locale parameter
  228. *
  229. * @param string $currency (Optional) Currency name
  230. * @param string|Zend_Locale $locale (Optional) Locale to display informations
  231. * @throws Zend_Currency_Exception When locale contains no region
  232. * @return string The extracted locale representation as string
  233. */
  234. private function _checkParams($currency = null, $locale = null)
  235. {
  236. // Manage the params
  237. if ((empty($locale)) and (!empty($currency)) and
  238. (Zend_Locale::isLocale($currency, true, false))) {
  239. $locale = $currency;
  240. $currency = null;
  241. }
  242. // Validate the locale and get the country short name
  243. $country = null;
  244. if ((Zend_Locale::isLocale($locale, true, false)) and (strlen($locale) > 4)) {
  245. $country = substr($locale, (strpos($locale, '_') + 1));
  246. } else {
  247. require_once 'Zend/Currency/Exception.php';
  248. throw new Zend_Currency_Exception("No region found within the locale '" . (string) $locale . "'");
  249. }
  250. // Get the available currencies for this country
  251. $data = Zend_Locale_Data::getContent($locale, 'currencytoregion', $country);
  252. if ((empty($currency) === false) and (empty($data) === false)) {
  253. $abbreviation = $currency;
  254. } else {
  255. $abbreviation = $data;
  256. }
  257. return array('locale' => $locale, 'currency' => $currency, 'name' => $abbreviation, 'country' => $country);
  258. }
  259. /**
  260. * Returns the actual or details of other currency symbols,
  261. * when no symbol is available it returns the currency shortname (f.e. FIM for Finnian Mark)
  262. *
  263. * @param string $currency (Optional) Currency name
  264. * @param string|Zend_Locale $locale (Optional) Locale to display informations
  265. * @return string
  266. */
  267. public function getSymbol($currency = null, $locale = null)
  268. {
  269. if (($currency === null) and ($locale === null)) {
  270. return $this->_options['symbol'];
  271. }
  272. $params = self::_checkParams($currency, $locale);
  273. // Get the symbol
  274. $symbol = Zend_Locale_Data::getContent($params['locale'], 'currencysymbol', $params['currency']);
  275. if (empty($symbol) === true) {
  276. $symbol = Zend_Locale_Data::getContent($params['locale'], 'currencysymbol', $params['name']);
  277. }
  278. if (empty($symbol) === true) {
  279. return null;
  280. }
  281. return $symbol;
  282. }
  283. /**
  284. * Returns the actual or details of other currency shortnames
  285. *
  286. * @param string $currency OPTIONAL Currency's name
  287. * @param string|Zend_Locale $locale OPTIONAL The locale
  288. * @return string
  289. */
  290. public function getShortName($currency = null, $locale = null)
  291. {
  292. if (($currency === null) and ($locale === null)) {
  293. return $this->_options['currency'];
  294. }
  295. $params = self::_checkParams($currency, $locale);
  296. // Get the shortname
  297. if (empty($params['currency']) === true) {
  298. return $params['name'];
  299. }
  300. $list = Zend_Locale_Data::getContent($params['locale'], 'currencytoname', $params['currency']);
  301. if (empty($list) === true) {
  302. $list = Zend_Locale_Data::getContent($params['locale'], 'nametocurrency', $params['currency']);
  303. if (empty($list) === false) {
  304. $list = $params['currency'];
  305. }
  306. }
  307. if (empty($list) === true) {
  308. return null;
  309. }
  310. return $list;
  311. }
  312. /**
  313. * Returns the actual or details of other currency names
  314. *
  315. * @param string $currency (Optional) Currency's short name
  316. * @param string|Zend_Locale $locale (Optional) The locale
  317. * @return string
  318. */
  319. public function getName($currency = null, $locale = null)
  320. {
  321. if (($currency === null) and ($locale === null)) {
  322. return $this->_options['name'];
  323. }
  324. $params = self::_checkParams($currency, $locale);
  325. // Get the name
  326. $name = Zend_Locale_Data::getContent($params['locale'], 'nametocurrency', $params['currency']);
  327. if (empty($name) === true) {
  328. $name = Zend_Locale_Data::getContent($params['locale'], 'nametocurrency', $params['name']);
  329. }
  330. if (empty($name) === true) {
  331. return null;
  332. }
  333. return $name;
  334. }
  335. /**
  336. * Returns a list of regions where this currency is or was known
  337. *
  338. * @param string $currency OPTIONAL Currency's short name
  339. * @throws Zend_Currency_Exception When no currency was defined
  340. * @return array List of regions
  341. */
  342. public function getRegionList($currency = null)
  343. {
  344. if ($currency === null) {
  345. $currency = $this->_options['currency'];
  346. }
  347. if (empty($currency) === true) {
  348. require_once 'Zend/Currency/Exception.php';
  349. throw new Zend_Currency_Exception('No currency defined');
  350. }
  351. $data = Zend_Locale_Data::getContent('', 'regiontocurrency', $currency);
  352. $result = explode(' ', $data);
  353. return $result;
  354. }
  355. /**
  356. * Returns a list of currencies which are used in this region
  357. * a region name should be 2 charachters only (f.e. EG, DE, US)
  358. * If no region is given, the actual region is used
  359. *
  360. * @param string $region OPTIONAL Region to return the currencies for
  361. * @return array List of currencies
  362. */
  363. public function getCurrencyList($region = null)
  364. {
  365. if (empty($region) === true) {
  366. if (strlen($this->_locale) > 4) {
  367. $region = substr($this->_locale, (strpos($this->_locale, '_') + 1));
  368. }
  369. }
  370. return Zend_Locale_Data::getList('', 'regiontocurrency', $region);
  371. }
  372. /**
  373. * Returns the actual currency name
  374. *
  375. * @return string
  376. */
  377. public function toString()
  378. {
  379. return (empty($this->_options['name']) === false) ? $this->_options['name'] : $this->_options['currency'];
  380. }
  381. /**
  382. * Returns the currency name
  383. *
  384. * @return string
  385. */
  386. public function __toString()
  387. {
  388. return $this->toString();
  389. }
  390. /**
  391. * Returns the set cache
  392. *
  393. * @return Zend_Cache_Core The set cache
  394. */
  395. public static function getCache()
  396. {
  397. $cache = Zend_Locale_Data::getCache();
  398. return $cache;
  399. }
  400. /**
  401. * Sets a cache for Zend_Currency
  402. *
  403. * @param Zend_Cache_Core $cache Cache to set
  404. * @return void
  405. */
  406. public static function setCache(Zend_Cache_Core $cache)
  407. {
  408. Zend_Locale_Data::setCache($cache);
  409. }
  410. /**
  411. * Returns true when a cache is set
  412. *
  413. * @return boolean
  414. */
  415. public static function hasCache()
  416. {
  417. return Zend_Locale_Data::hasCache();
  418. }
  419. /**
  420. * Removes any set cache
  421. *
  422. * @return void
  423. */
  424. public static function removeCache()
  425. {
  426. Zend_Locale_Data::removeCache();
  427. }
  428. /**
  429. * Clears all set cache data
  430. *
  431. * @return void
  432. */
  433. public static function clearCache()
  434. {
  435. Zend_Locale_Data::clearCache();
  436. }
  437. /**
  438. * Sets a new locale for data retreivement
  439. * Example: 'de_XX' will be set to 'de' because 'de_XX' does not exist
  440. * 'xx_YY' will be set to 'root' because 'xx' does not exist
  441. *
  442. * @param string|Zend_Locale $locale (Optional) Locale for parsing input
  443. * @throws Zend_Currency_Exception When the given locale does not exist
  444. * @return Zend_Currency Provides fluent interface
  445. */
  446. public function setLocale($locale = null)
  447. {
  448. require_once 'Zend/Locale.php';
  449. try {
  450. $this->_locale = Zend_Locale::findLocale($locale);
  451. } catch (Zend_Locale_Exception $e) {
  452. require_once 'Zend/Currency/Exception.php';
  453. throw new Zend_Currency_Exception($e->getMessage());
  454. }
  455. // Get currency details
  456. $this->_options['currency'] = $this->getShortName(null, $this->_locale);
  457. $this->_options['name'] = $this->getName(null, $this->_locale);
  458. $this->_options['symbol'] = $this->getSymbol(null, $this->_locale);
  459. return $this;
  460. }
  461. /**
  462. * Returns the actual set locale
  463. *
  464. * @return string
  465. */
  466. public function getLocale()
  467. {
  468. return $this->_locale;
  469. }
  470. /**
  471. * Internal method for checking the options array
  472. *
  473. * @param array $options Options to check
  474. * @throws Zend_Currency_Exception On unknown position
  475. * @throws Zend_Currency_Exception On unknown locale
  476. * @throws Zend_Currency_Exception On unknown display
  477. * @throws Zend_Currency_Exception On precision not between -1 and 30
  478. * @throws Zend_Currency_Exception On problem with script conversion
  479. * @throws Zend_Currency_Exception On unknown options
  480. * @return array
  481. */
  482. private function _checkOptions(array $options = array())
  483. {
  484. if (count($options) === 0) {
  485. return $this->_options;
  486. }
  487. foreach ($options as $name => $value) {
  488. $name = strtolower($name);
  489. if ($name !== 'format') {
  490. if (gettype($value) === 'string') {
  491. $value = strtolower($value);
  492. }
  493. }
  494. switch($name) {
  495. case 'position':
  496. if (($value !== self::STANDARD) and ($value !== self::RIGHT) and ($value !== self::LEFT)) {
  497. require_once 'Zend/Currency/Exception.php';
  498. throw new Zend_Currency_Exception("Unknown position '" . $value . "'");
  499. }
  500. break;
  501. case 'format':
  502. if ((empty($value) === false) and (Zend_Locale::isLocale($value, null, false) === false)) {
  503. require_once 'Zend/Currency/Exception.php';
  504. throw new Zend_Currency_Exception("'" .
  505. ((gettype($value) === 'object') ? get_class($value) : $value)
  506. . "' is not a known locale.");
  507. }
  508. break;
  509. case 'display':
  510. if (is_numeric($value) and ($value !== self::NO_SYMBOL) and ($value !== self::USE_SYMBOL) and
  511. ($value !== self::USE_SHORTNAME) and ($value !== self::USE_NAME)) {
  512. require_once 'Zend/Currency/Exception.php';
  513. throw new Zend_Currency_Exception("Unknown display '$value'");
  514. }
  515. break;
  516. case 'precision':
  517. if ($value === null) {
  518. $value = -1;
  519. }
  520. if (($value < -1) or ($value > 30)) {
  521. require_once 'Zend/Currency/Exception.php';
  522. throw new Zend_Currency_Exception("'$value' precision has to be between -1 and 30.");
  523. }
  524. break;
  525. case 'script':
  526. try {
  527. Zend_Locale_Format::convertNumerals(0, $options['script']);
  528. } catch (Zend_Locale_Exception $e) {
  529. require_once 'Zend/Currency/Exception.php';
  530. throw new Zend_Currency_Exception($e->getMessage());
  531. }
  532. break;
  533. case 'name':
  534. // Break intentionally omitted
  535. case 'currency':
  536. // Break intentionally omitted
  537. case 'symbol':
  538. // Unchecked options
  539. break;
  540. default:
  541. require_once 'Zend/Currency/Exception.php';
  542. throw new Zend_Currency_Exception("Unknown option: '$name' = '$value'");
  543. break;
  544. }
  545. }
  546. return $options;
  547. }
  548. }