NumberFormatter.php 28 KB

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