StubNumberFormatter.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Locale\Stub;
  11. use Symfony\Component\Locale\Stub\StubLocale;
  12. use Symfony\Component\Locale\Exception\NotImplementedException;
  13. use Symfony\Component\Locale\Exception\MethodNotImplementedException;
  14. use Symfony\Component\Locale\Exception\MethodArgumentNotImplementedException;
  15. use Symfony\Component\Locale\Exception\MethodArgumentValueNotImplementedException;
  16. /**
  17. * Provides a stub NumberFormatter for the 'en' locale.
  18. *
  19. * @author Eriksen Costa <eriksen.costa@infranology.com.br>
  20. */
  21. class StubNumberFormatter
  22. {
  23. /**
  24. * The error code from the last operation
  25. *
  26. * @var integer
  27. */
  28. protected $errorCode = StubIntl::U_ZERO_ERROR;
  29. /**
  30. * The error message from the last operation
  31. *
  32. * @var string
  33. */
  34. protected $errorMessage = 'U_ZERO_ERROR';
  35. /** Format style constants */
  36. const PATTERN_DECIMAL = 0;
  37. const DECIMAL = 1;
  38. const CURRENCY = 2;
  39. const PERCENT = 3;
  40. const SCIENTIFIC = 4;
  41. const SPELLOUT = 5;
  42. const ORDINAL = 6;
  43. const DURATION = 7;
  44. const PATTERN_RULEBASED = 9;
  45. const IGNORE = 0;
  46. const DEFAULT_STYLE = 1;
  47. /** Format type constants */
  48. const TYPE_DEFAULT = 0;
  49. const TYPE_INT32 = 1;
  50. const TYPE_INT64 = 2;
  51. const TYPE_DOUBLE = 3;
  52. const TYPE_CURRENCY = 4;
  53. /** Numeric attribute constants */
  54. const PARSE_INT_ONLY = 0;
  55. const GROUPING_USED = 1;
  56. const DECIMAL_ALWAYS_SHOWN = 2;
  57. const MAX_INTEGER_DIGITS = 3;
  58. const MIN_INTEGER_DIGITS = 4;
  59. const INTEGER_DIGITS = 5;
  60. const MAX_FRACTION_DIGITS = 6;
  61. const MIN_FRACTION_DIGITS = 7;
  62. const FRACTION_DIGITS = 8;
  63. const MULTIPLIER = 9;
  64. const GROUPING_SIZE = 10;
  65. const ROUNDING_MODE = 11;
  66. const ROUNDING_INCREMENT = 12;
  67. const FORMAT_WIDTH = 13;
  68. const PADDING_POSITION = 14;
  69. const SECONDARY_GROUPING_SIZE = 15;
  70. const SIGNIFICANT_DIGITS_USED = 16;
  71. const MIN_SIGNIFICANT_DIGITS = 17;
  72. const MAX_SIGNIFICANT_DIGITS = 18;
  73. const LENIENT_PARSE = 19;
  74. /** Text attribute constants */
  75. const POSITIVE_PREFIX = 0;
  76. const POSITIVE_SUFFIX = 1;
  77. const NEGATIVE_PREFIX = 2;
  78. const NEGATIVE_SUFFIX = 3;
  79. const PADDING_CHARACTER = 4;
  80. const CURRENCY_CODE = 5;
  81. const DEFAULT_RULESET = 6;
  82. const PUBLIC_RULESETS = 7;
  83. /** Format symbol constants */
  84. const DECIMAL_SEPARATOR_SYMBOL = 0;
  85. const GROUPING_SEPARATOR_SYMBOL = 1;
  86. const PATTERN_SEPARATOR_SYMBOL = 2;
  87. const PERCENT_SYMBOL = 3;
  88. const ZERO_DIGIT_SYMBOL = 4;
  89. const DIGIT_SYMBOL = 5;
  90. const MINUS_SIGN_SYMBOL = 6;
  91. const PLUS_SIGN_SYMBOL = 7;
  92. const CURRENCY_SYMBOL = 8;
  93. const INTL_CURRENCY_SYMBOL = 9;
  94. const MONETARY_SEPARATOR_SYMBOL = 10;
  95. const EXPONENTIAL_SYMBOL = 11;
  96. const PERMILL_SYMBOL = 12;
  97. const PAD_ESCAPE_SYMBOL = 13;
  98. const INFINITY_SYMBOL = 14;
  99. const NAN_SYMBOL = 15;
  100. const SIGNIFICANT_DIGIT_SYMBOL = 16;
  101. const MONETARY_GROUPING_SEPARATOR_SYMBOL = 17;
  102. /** Rounding mode values used by NumberFormatter::setAttribute() with NumberFormatter::ROUNDING_MODE attribute */
  103. const ROUND_CEILING = 0;
  104. const ROUND_FLOOR = 1;
  105. const ROUND_DOWN = 2;
  106. const ROUND_UP = 3;
  107. const ROUND_HALFEVEN = 4;
  108. const ROUND_HALFDOWN = 5;
  109. const ROUND_HALFUP = 6;
  110. /** Pad position values used by NumberFormatter::setAttribute() with NumberFormatter::PADDING_POSITION attribute */
  111. const PAD_BEFORE_PREFIX = 0;
  112. const PAD_AFTER_PREFIX = 1;
  113. const PAD_BEFORE_SUFFIX = 2;
  114. const PAD_AFTER_SUFFIX = 3;
  115. /**
  116. * Default values for the en locale
  117. *
  118. * @var array
  119. */
  120. private $attributes = array(
  121. self::FRACTION_DIGITS => 0,
  122. self::GROUPING_USED => 1,
  123. self::ROUNDING_MODE => self::ROUND_HALFEVEN
  124. );
  125. /**
  126. * Holds the initialized attributes code
  127. *
  128. * @var array
  129. */
  130. private $initializedAttributes = array();
  131. /**
  132. * The supported styles to the constructor $styles argument
  133. *
  134. * @var array
  135. */
  136. static private $supportedStyles = array(
  137. 'CURRENCY' => self::CURRENCY,
  138. 'DECIMAL' => self::DECIMAL
  139. );
  140. /**
  141. * Supported attributes to the setAttribute() $attr argument
  142. *
  143. * @var array
  144. */
  145. static private $supportedAttributes = array(
  146. 'FRACTION_DIGITS' => self::FRACTION_DIGITS,
  147. 'GROUPING_USED' => self::GROUPING_USED,
  148. 'ROUNDING_MODE' => self::ROUNDING_MODE
  149. );
  150. /**
  151. * The available rounding modes for setAttribute() usage with
  152. * StubNumberFormatter::ROUNDING_MODE. StubNumberFormatter::ROUND_DOWN
  153. * and StubNumberFormatter::ROUND_UP does not have a PHP only equivalent
  154. *
  155. * @var array
  156. */
  157. static private $roundingModes = array(
  158. 'ROUND_HALFEVEN' => self::ROUND_HALFEVEN,
  159. 'ROUND_HALFDOWN' => self::ROUND_HALFDOWN,
  160. 'ROUND_HALFUP' => self::ROUND_HALFUP
  161. );
  162. /**
  163. * The mapping between NumberFormatter rounding modes to the available
  164. * modes in PHP's round() function.
  165. *
  166. * @see http://www.php.net/manual/en/function.round.php
  167. *
  168. * @var array
  169. */
  170. static private $phpRoundingMap = array(
  171. self::ROUND_HALFDOWN => \PHP_ROUND_HALF_DOWN,
  172. self::ROUND_HALFEVEN => \PHP_ROUND_HALF_EVEN,
  173. self::ROUND_HALFUP => \PHP_ROUND_HALF_UP
  174. );
  175. /**
  176. * The maximum values of the integer type in 32 bit platforms.
  177. *
  178. * @var array
  179. */
  180. static private $int32Range = array(
  181. 'positive' => 2147483647,
  182. 'negative' => -2147483648
  183. );
  184. /**
  185. * The maximum values of the integer type in 64 bit platforms.
  186. *
  187. * @var array
  188. */
  189. static private $int64Range = array(
  190. 'positive' => 9223372036854775807,
  191. 'negative' => -9223372036854775808
  192. );
  193. /**
  194. * @var string
  195. */
  196. private $locale = null;
  197. /**
  198. * @var int
  199. */
  200. private $style = null;
  201. /**
  202. * Constructor
  203. *
  204. * @param string $locale The locale code
  205. * @param int $style Style of the formatting, one of the format style constants
  206. * @param string $pattern A pattern string in case $style is NumberFormat::PATTERN_DECIMAL or
  207. * NumberFormat::PATTERN_RULEBASED. It must conform to the syntax
  208. * described in the ICU DecimalFormat or ICU RuleBasedNumberFormat documentation
  209. *
  210. * @see http://www.php.net/manual/en/numberformatter.create.php
  211. * @see http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details
  212. * @see http://www.icu-project.org/apiref/icu4c/classRuleBasedNumberFormat.html#_details
  213. *
  214. * @throws MethodArgumentValueNotImplementedException When $locale different than 'en' is passed
  215. * @throws MethodArgumentValueNotImplementedException When the $style is not supported
  216. * @throws MethodArgumentNotImplementedException When the pattern value is different than null
  217. */
  218. public function __construct($locale = 'en', $style = null, $pattern = null)
  219. {
  220. if ('en' != $locale) {
  221. throw new MethodArgumentValueNotImplementedException(__METHOD__, 'locale', $locale, 'Only the \'en\' locale is supported');
  222. }
  223. if (!in_array($style, self::$supportedStyles)) {
  224. $message = sprintf('The available styles are: %s.', implode(', ', array_keys(self::$supportedStyles)));
  225. throw new MethodArgumentValueNotImplementedException(__METHOD__, 'style', $style, $message);
  226. }
  227. if (null !== $pattern) {
  228. throw new MethodArgumentNotImplementedException(__METHOD__, 'pattern');
  229. }
  230. $this->locale = $locale;
  231. $this->style = $style;
  232. }
  233. /**
  234. * Static constructor
  235. *
  236. * @param string $locale The locale code
  237. * @param int $style Style of the formatting, one of the format style constants
  238. * @param string $pattern A pattern string in case $style is NumberFormat::PATTERN_DECIMAL or
  239. * NumberFormat::PATTERN_RULEBASED. It must conform to the syntax
  240. * described in the ICU DecimalFormat or ICU RuleBasedNumberFormat documentation
  241. *
  242. * @see http://www.php.net/manual/en/numberformatter.create.php
  243. * @see http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details
  244. * @see http://www.icu-project.org/apiref/icu4c/classRuleBasedNumberFormat.html#_details
  245. *
  246. * @throws MethodArgumentValueNotImplementedException When $locale different than 'en' is passed
  247. * @throws MethodArgumentValueNotImplementedException When the $style is not supported
  248. * @throws MethodArgumentNotImplementedException When the pattern value is different than null
  249. */
  250. static public function create($locale = 'en', $style = null, $pattern = null)
  251. {
  252. return new self($locale, $style, $pattern);
  253. }
  254. /**
  255. * Format a currency value
  256. *
  257. * @param float $value The numeric currency value
  258. * @param string $currency The 3-letter ISO 4217 currency code indicating the currency to use
  259. *
  260. * @return string The formatted currency value
  261. *
  262. * @see http://www.php.net/manual/en/numberformatter.formatcurrency.php
  263. * @see http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/currency_codes/currency_codes_list-1.htm
  264. */
  265. public function formatCurrency($value, $currency)
  266. {
  267. if ($this->style == self::DECIMAL) {
  268. return $this->format($value);
  269. }
  270. $symbol = $this->getCurrencySymbol($currency);
  271. $fractionDigits = $this->getCurrencyFractionDigits($currency);
  272. $value = $this->roundCurrency($value, $currency);
  273. $negative = false;
  274. if (0 > $value) {
  275. $negative = true;
  276. $value *= -1;
  277. }
  278. $value = $this->formatNumber($value, $fractionDigits);
  279. $ret = $symbol.$value;
  280. return $negative ? '('.$ret.')' : $ret;
  281. }
  282. /**
  283. * Format a number
  284. *
  285. * @param number $value The value to format
  286. * @param int $type Type of the formatting, one of the format type constants
  287. *
  288. * @return Boolean|string The formatted value or false on error
  289. *
  290. * @see http://www.php.net/manual/en/numberformatter.format.php
  291. *
  292. * @throws RuntimeException If the method is called with the class $style 'CURRENCY'
  293. * @throws MethodArgumentNotImplementedException If the $type is different than TYPE_DEFAULT
  294. */
  295. public function format($value, $type = self::TYPE_DEFAULT)
  296. {
  297. // The original NumberFormatter does not support this format type
  298. if ($type == self::TYPE_CURRENCY) {
  299. trigger_error(__METHOD__.'(): Unsupported format type '.$type, \E_USER_WARNING);
  300. return false;
  301. }
  302. if ($this->style == self::CURRENCY) {
  303. throw new \RuntimeException(sprintf(
  304. '%s() method does not support the formatting of currencies (instance with CURRENCY style). %s',
  305. __METHOD__, NotImplementedException::INTL_INSTALL_MESSAGE
  306. ));
  307. }
  308. // Only the default type is supported.
  309. if ($type != self::TYPE_DEFAULT) {
  310. throw new MethodArgumentValueNotImplementedException(__METHOD__, 'type', $type, 'Only TYPE_DEFAULT is supported');
  311. }
  312. $fractionDigits = $this->getAttribute(self::FRACTION_DIGITS);
  313. $value = $this->round($value, $fractionDigits);
  314. return $this->formatNumber($value, $fractionDigits);
  315. }
  316. /**
  317. * Returns an attribute value
  318. *
  319. * @param int $attr An attribute specifier, one of the numeric attribute constants
  320. *
  321. * @return Boolean|int The attribute value on success or false on error
  322. *
  323. * @see http://www.php.net/manual/en/numberformatter.getattribute.php
  324. */
  325. public function getAttribute($attr)
  326. {
  327. return isset($this->attributes[$attr]) ? $this->attributes[$attr] : null;
  328. }
  329. /**
  330. * Returns formatter's last error code. Always returns the U_ZERO_ERROR class constant value
  331. *
  332. * @return int The error code from last formatter call
  333. *
  334. * @see http://www.php.net/manual/en/numberformatter.geterrorcode.php
  335. */
  336. public function getErrorCode()
  337. {
  338. return $this->errorCode;
  339. }
  340. /**
  341. * Returns formatter's last error message. Always returns the U_ZERO_ERROR_MESSAGE class constant value
  342. *
  343. * @return string The error message from last formatter call
  344. *
  345. * @see http://www.php.net/manual/en/numberformatter.geterrormessage.php
  346. */
  347. public function getErrorMessage()
  348. {
  349. return $this->errorMessage;
  350. }
  351. /**
  352. * Returns the formatter's locale
  353. *
  354. * @param int $type The locale name type to return between valid or actual (StubLocale::VALID_LOCALE or StubLocale::ACTUAL_LOCALE, respectively)
  355. *
  356. * @return string The locale name used to create the formatter
  357. *
  358. * @see http://www.php.net/manual/en/numberformatter.getlocale.php
  359. */
  360. public function getLocale($type = StubLocale::ACTUAL_LOCALE)
  361. {
  362. return $this->locale;
  363. }
  364. /**
  365. * Returns the formatter's pattern
  366. *
  367. * @return Boolean|string The pattern string used by the formatter or false on error
  368. *
  369. * @see http://www.php.net/manual/en/numberformatter.getpattern.php
  370. *
  371. * @throws MethodNotImplementedException
  372. */
  373. public function getPattern()
  374. {
  375. throw new MethodNotImplementedException(__METHOD__);
  376. }
  377. /**
  378. * Returns a formatter symbol value
  379. *
  380. * @param int $attr A symbol specifier, one of the format symbol constants
  381. *
  382. * @return Boolean|string The symbol value or false on error
  383. *
  384. * @see http://www.php.net/manual/en/numberformatter.getsymbol.php
  385. *
  386. * @throws MethodNotImplementedException
  387. */
  388. public function getSymbol($attr)
  389. {
  390. throw new MethodNotImplementedException(__METHOD__);
  391. }
  392. /**
  393. * Returns a formatter text attribute value
  394. *
  395. * @param int $attr An attribute specifier, one of the text attribute constants
  396. *
  397. * @return Boolean|string The attribute value or false on error
  398. *
  399. * @see http://www.php.net/manual/en/numberformatter.gettextattribute.php
  400. *
  401. * @throws MethodNotImplementedException
  402. */
  403. public function getTextAttribute($attr)
  404. {
  405. throw new MethodNotImplementedException(__METHOD__);
  406. }
  407. /**
  408. * Parse a currency number
  409. *
  410. * @param string $value The value to parse
  411. * @param string $currency Parameter to receive the currency name (reference)
  412. * @param int $position Offset to begin the parsing on return this value will hold the offset at which the parsing ended
  413. *
  414. * @return Boolean|string The parsed numeric value of false on error
  415. *
  416. * @see http://www.php.net/manual/en/numberformatter.parsecurrency.php
  417. *
  418. * @throws MethodNotImplementedException
  419. */
  420. public function parseCurrency($value, &$currency, &$position = null)
  421. {
  422. throw new MethodNotImplementedException(__METHOD__);
  423. }
  424. /**
  425. * Parse a number
  426. *
  427. * @param string $value The value to parse
  428. * @param string $type Type of the formatting, one of the format type constants. NumberFormatter::TYPE_DOUBLE by default
  429. * @param int $position Offset to begin the parsing on return this value will hold the offset at which the parsing ended
  430. *
  431. * @return Boolean|string The parsed value of false on error
  432. *
  433. * @see http://www.php.net/manual/en/numberformatter.parse.php
  434. *
  435. * @throws MethodArgumentNotImplementedException When $position different than null, behavior not implemented
  436. */
  437. public function parse($value, $type = self::TYPE_DOUBLE, &$position = null)
  438. {
  439. if ($type == self::TYPE_DEFAULT || $type == self::TYPE_CURRENCY) {
  440. trigger_error(__METHOD__.'(): Unsupported format type '.$type, \E_USER_WARNING);
  441. return false;
  442. }
  443. // We don't calculate the position when parsing the value
  444. if (null !== $position) {
  445. throw new MethodArgumentNotImplementedException(__METHOD__, 'position');
  446. }
  447. preg_match('/^([^0-9\-]{0,})(.*)/', $value, $matches);
  448. // Any string before the numeric value causes error in the parsing
  449. if (isset($matches[1]) && !empty($matches[1])) {
  450. StubIntl::setError(StubIntl::U_PARSE_ERROR);
  451. $this->errorCode = StubIntl::getErrorCode();
  452. $this->errorMessage = StubIntl::getErrorMessage();
  453. return false;
  454. }
  455. // Remove everything that is not number or dot (.)
  456. $value = preg_replace('/[^0-9\.\-]/', '', $value);
  457. return $this->convertValueDataType($value, $type);
  458. }
  459. /**
  460. * Set an attribute
  461. *
  462. * @param int $attr An attribute specifier, one of the numeric attribute constants
  463. * @param int $value The attribute value
  464. *
  465. * @return Boolean true on success or false on failure
  466. *
  467. * @see http://www.php.net/manual/en/numberformatter.setattribute.php
  468. *
  469. * @throws MethodArgumentValueNotImplementedException When the $attr is not supported
  470. * @throws MethodArgumentValueNotImplementedException When the $value is not supported
  471. */
  472. public function setAttribute($attr, $value)
  473. {
  474. if (!in_array($attr, self::$supportedAttributes)) {
  475. $message = sprintf(
  476. 'The available attributes are: %s',
  477. implode(', ', array_keys(self::$supportedAttributes))
  478. );
  479. throw new MethodArgumentValueNotImplementedException(__METHOD__, 'attr', $value, $message);
  480. }
  481. if (self::$supportedAttributes['ROUNDING_MODE'] == $attr && $this->isInvalidRoundingMode($value)) {
  482. $message = sprintf(
  483. 'The supported values for ROUNDING_MODE are: %s',
  484. implode(', ', array_keys(self::$roundingModes))
  485. );
  486. throw new MethodArgumentValueNotImplementedException(__METHOD__, 'attr', $value, $message);
  487. }
  488. if (self::$supportedAttributes['GROUPING_USED'] == $attr) {
  489. $value = $this->normalizeGroupingUsedValue($value);
  490. }
  491. if (self::$supportedAttributes['FRACTION_DIGITS'] == $attr) {
  492. $value = $this->normalizeFractionDigitsValue($value);
  493. }
  494. $this->attributes[$attr] = $value;
  495. $this->initializedAttributes[$attr] = true;
  496. return true;
  497. }
  498. /**
  499. * Set the formatter's pattern
  500. *
  501. * @param string $pattern A pattern string in conformance with the ICU DecimalFormat documentation
  502. *
  503. * @return Boolean true on success or false on failure
  504. *
  505. * @see http://www.php.net/manual/en/numberformatter.setpattern.php
  506. * @see http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details
  507. *
  508. * @throws MethodNotImplementedException
  509. */
  510. public function setPattern($pattern)
  511. {
  512. throw new MethodNotImplementedException(__METHOD__);
  513. }
  514. /**
  515. * Set the formatter's symbol
  516. *
  517. * @param int $attr A symbol specifier, one of the format symbol constants
  518. * @param string $value The value for the symbol
  519. *
  520. * @return Boolean true on success or false on failure
  521. *
  522. * @see http://www.php.net/manual/en/numberformatter.setsymbol.php
  523. *
  524. * @throws MethodNotImplementedException
  525. */
  526. public function setSymbol($attr, $value)
  527. {
  528. throw new MethodNotImplementedException(__METHOD__);
  529. }
  530. /**
  531. * Set a text attribute
  532. *
  533. * @param int $attr An attribute specifier, one of the text attribute constants
  534. * @param int $value The attribute value
  535. *
  536. * @return Boolean true on success or false on failure
  537. *
  538. * @see http://www.php.net/manual/en/numberformatter.settextattribute.php
  539. *
  540. * @throws MethodNotImplementedException
  541. */
  542. public function setTextAttribute($attr, $value)
  543. {
  544. throw new MethodNotImplementedException(__METHOD__);
  545. }
  546. /**
  547. * Rounds a currency value, applying increment rounding if applicable
  548. *
  549. * When a currency have a rounding increment, an extra round is made after the first one. The rounding factor is
  550. * determined in the ICU data and is explained as of:
  551. *
  552. * "the rounding increment is given in units of 10^(-fraction_digits)"
  553. *
  554. * The only actual rounding data as of this writing, is CHF.
  555. *
  556. * @param float $value The numeric currency value
  557. * @param string $currency The 3-letter ISO 4217 currency code indicating the currency to use
  558. *
  559. * @return string The rounded numeric currency value
  560. *
  561. * @see http://en.wikipedia.org/wiki/Swedish_rounding
  562. * @see http://www.docjar.com/html/api/com/ibm/icu/util/Currency.java.html#1007
  563. */
  564. private function roundCurrency($value, $currency)
  565. {
  566. $fractionDigits = $this->getCurrencyFractionDigits($currency);
  567. $roundingIncrement = $this->getCurrencyRoundingIncrement($currency);
  568. // Round with the formatter rounding mode
  569. $value = $this->round($value, $fractionDigits);
  570. // Swiss rounding
  571. if (0 < $roundingIncrement && 0 < $fractionDigits) {
  572. $roundingFactor = $roundingIncrement / pow(10, $fractionDigits);
  573. $value = round($value / $roundingFactor) * $roundingFactor;
  574. }
  575. return $value;
  576. }
  577. /**
  578. * Returns the currency symbol
  579. *
  580. * @param string $currency The 3-letter ISO 4217 currency code indicating the currency to use
  581. *
  582. * @return string The currency symbol
  583. */
  584. private function getCurrencySymbol($currency)
  585. {
  586. $currencies = StubLocale::getCurrenciesData($this->locale);
  587. return $currencies[$currency]['symbol'];
  588. }
  589. /**
  590. * Returns the fraction digits of a currency
  591. *
  592. * @param string $currency The 3-letter ISO 4217 currency code indicating the currency to use
  593. *
  594. * @return string The fraction digits of a currency
  595. */
  596. private function getCurrencyFractionDigits($currency)
  597. {
  598. $currencies = StubLocale::getCurrenciesData($this->locale);
  599. return $currencies[$currency]['fractionDigits'];
  600. }
  601. /**
  602. * Returns the rounding increment of a currency
  603. *
  604. * @param string $currency The 3-letter ISO 4217 currency code indicating the currency to use
  605. *
  606. * @return string The rounding increment of a currency
  607. */
  608. private function getCurrencyRoundingIncrement($currency)
  609. {
  610. $currencies = StubLocale::getCurrenciesData($this->locale);
  611. return $currencies[$currency]['roundingIncrement'];
  612. }
  613. /**
  614. * Rounds a value.
  615. *
  616. * @param numeric $value The value to round
  617. * @param int $precision The number of decimal digits to round to
  618. *
  619. * @return numeric The rounded value
  620. */
  621. private function round($value, $precision)
  622. {
  623. $precision = $this->getUnitializedPrecision($value, $precision);
  624. $roundingMode = self::$phpRoundingMap[$this->getAttribute(self::ROUNDING_MODE)];
  625. $value = round($value, $precision, $roundingMode);
  626. return $value;
  627. }
  628. /**
  629. * Formats a number.
  630. *
  631. * @param numeric $value The numeric value to format
  632. * @param int $precision The number of decimal digits to use
  633. *
  634. * @return string The formatted number
  635. */
  636. private function formatNumber($value, $precision)
  637. {
  638. $precision = $this->getUnitializedPrecision($value, $precision);
  639. return number_format($value, $precision, '.', $this->getAttribute(self::GROUPING_USED) ? ',' : '');
  640. }
  641. /**
  642. * Returns the precision value if the the DECIMAL style is being used and the FRACTION_DIGITS attribute is unitialized.
  643. *
  644. * @param numeric $value The value to get the precision from if the FRACTION_DIGITS attribute is unitialized
  645. * @param int $precision The precision value to returns if the FRACTION_DIGITS attribute is initialized
  646. *
  647. * @return int The precision value
  648. */
  649. private function getUnitializedPrecision($value, $precision)
  650. {
  651. if ($this->style == self::CURRENCY) {
  652. return $precision;
  653. }
  654. if (!$this->isInitializedAttribute(self::FRACTION_DIGITS)) {
  655. preg_match('/.*\.(.*)/', (string) $value, $digits);
  656. if (isset($digits[1])) {
  657. $precision = strlen($digits[1]);
  658. }
  659. }
  660. return $precision;
  661. }
  662. /**
  663. * Check if the attribute is initialized (value set by client code).
  664. *
  665. * @param string $attr The attribute name
  666. *
  667. * @return Boolean true if the value was set by client, false otherwise
  668. */
  669. private function isInitializedAttribute($attr)
  670. {
  671. return isset($this->initializedAttributes[$attr]);
  672. }
  673. /**
  674. * Returns the numeric value using the $type to convert to the right data type.
  675. *
  676. * @param mixed $value The value to be converted
  677. * @param int $type The type to convert. Can be TYPE_DOUBLE (float) or TYPE_INT32 (int)
  678. *
  679. * @return numeric The converted value
  680. */
  681. private function convertValueDataType($value, $type)
  682. {
  683. if ($type == self::TYPE_DOUBLE) {
  684. $value = (float) $value;
  685. } elseif ($type == self::TYPE_INT32) {
  686. $value = $this->getInt32Value($value);
  687. } elseif ($type == self::TYPE_INT64) {
  688. $value = $this->getInt64Value($value);
  689. }
  690. return $value;
  691. }
  692. /**
  693. * Convert the value data type to int or returns false if the value is out of the integer value range.
  694. *
  695. * @param mixed $value The value to be converted
  696. *
  697. * @return int The converted value
  698. */
  699. private function getInt32Value($value)
  700. {
  701. if ($value > self::$int32Range['positive'] || $value < self::$int32Range['negative']) {
  702. return false;
  703. }
  704. return (int) $value;
  705. }
  706. /**
  707. * Convert the value data type to int or returns false if the value is out of the integer value range.
  708. *
  709. * @param mixed $value The value to be converted
  710. *
  711. * @return int|float The converted value
  712. */
  713. private function getInt64Value($value)
  714. {
  715. if ($value > self::$int64Range['positive'] || $value < self::$int64Range['negative']) {
  716. return false;
  717. }
  718. if (PHP_INT_SIZE !== 8 && ($value > self::$int32Range['positive'] || $value <= self::$int32Range['negative'])) {
  719. return (float) $value;
  720. }
  721. if (PHP_INT_SIZE === 8 && ($value > self::$int32Range['positive'] || $value < self::$int32Range['negative'])) {
  722. $value = (-2147483648 - ($value % -2147483648)) * ($value / abs($value));
  723. }
  724. return (int) $value;
  725. }
  726. /**
  727. * Check if the rounding mode is invalid.
  728. *
  729. * @param int $value The rounding mode value to check
  730. *
  731. * @return Boolean true if the rounding mode is invalid, false otherwise
  732. */
  733. private function isInvalidRoundingMode($value)
  734. {
  735. if (in_array($value, self::$roundingModes, true)) {
  736. return false;
  737. }
  738. return true;
  739. }
  740. /**
  741. * Returns the normalized value for the GROUPING_USED attribute. Any value that can be converted to int will be
  742. * cast to Boolean and then to int again. This way, negative values are converted to 1 and string values to 0.
  743. *
  744. * @param mixed $value The value to be normalized
  745. *
  746. * @return int The normalized value for the attribute (0 or 1)
  747. */
  748. private function normalizeGroupingUsedValue($value)
  749. {
  750. return (int) (Boolean) (int) $value;
  751. }
  752. /**
  753. * Returns the normalized value for the FRACTION_DIGITS attribute. The value is converted to int and if negative,
  754. * the returned value will be 0.
  755. *
  756. * @param mixed $value The value to be normalized
  757. *
  758. * @return int The normalized value for the attribute
  759. */
  760. private function normalizeFractionDigitsValue($value)
  761. {
  762. $value = (int) $value;
  763. return (0 > $value) ? 0 : $value;
  764. }
  765. }