StubNumberFormatter.php 30KB

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