Currency.php 21 KB

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