PageRenderTime 57ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Symfony/Component/Intl/NumberFormatter/NumberFormatter.php

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