Currency.php 21 KB

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