NumberFormatter.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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\Exception\NotImplementedException;
  12. use Symfony\Component\Intl\Exception\MethodNotImplementedException;
  13. use Symfony\Component\Intl\Exception\MethodArgumentNotImplementedException;
  14. use Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException;
  15. use Symfony\Component\Intl\Globals\IntlGlobals;
  16. use Symfony\Component\Intl\Intl;
  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. 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. * @var array
  141. */
  142. private $attributes = array(
  143. self::FRACTION_DIGITS => 0,
  144. self::GROUPING_USED => 1,
  145. self::ROUNDING_MODE => self::ROUND_HALFEVEN,
  146. );
  147. /**
  148. * Holds the initialized attributes code.
  149. *
  150. * @var array
  151. */
  152. private $initializedAttributes = array();
  153. /**
  154. * The supported styles to the constructor $styles argument.
  155. *
  156. * @var array
  157. */
  158. private static $supportedStyles = array(
  159. 'CURRENCY' => self::CURRENCY,
  160. 'DECIMAL' => self::DECIMAL,
  161. );
  162. /**
  163. * Supported attributes to the setAttribute() $attr argument.
  164. *
  165. * @var array
  166. */
  167. private static $supportedAttributes = array(
  168. 'FRACTION_DIGITS' => self::FRACTION_DIGITS,
  169. 'GROUPING_USED' => self::GROUPING_USED,
  170. 'ROUNDING_MODE' => self::ROUNDING_MODE,
  171. );
  172. /**
  173. * The available rounding modes for setAttribute() usage with
  174. * NumberFormatter::ROUNDING_MODE. NumberFormatter::ROUND_DOWN
  175. * and NumberFormatter::ROUND_UP does not have a PHP only equivalent.
  176. *
  177. * @var array
  178. */
  179. private static $roundingModes = array(
  180. 'ROUND_HALFEVEN' => self::ROUND_HALFEVEN,
  181. 'ROUND_HALFDOWN' => self::ROUND_HALFDOWN,
  182. 'ROUND_HALFUP' => self::ROUND_HALFUP,
  183. 'ROUND_CEILING' => self::ROUND_CEILING,
  184. 'ROUND_FLOOR' => self::ROUND_FLOOR,
  185. 'ROUND_DOWN' => self::ROUND_DOWN,
  186. 'ROUND_UP' => self::ROUND_UP,
  187. );
  188. /**
  189. * The mapping between NumberFormatter rounding modes to the available
  190. * modes in PHP's round() function.
  191. *
  192. * @see http://www.php.net/manual/en/function.round.php
  193. *
  194. * @var array
  195. */
  196. private static $phpRoundingMap = array(
  197. self::ROUND_HALFDOWN => \PHP_ROUND_HALF_DOWN,
  198. self::ROUND_HALFEVEN => \PHP_ROUND_HALF_EVEN,
  199. self::ROUND_HALFUP => \PHP_ROUND_HALF_UP,
  200. );
  201. /**
  202. * The list of supported rounding modes which aren't available modes in
  203. * PHP's round() function, but there's an equivalent. Keys are rounding
  204. * modes, values does not matter.
  205. *
  206. * @var array
  207. */
  208. private static $customRoundingList = array(
  209. self::ROUND_CEILING => true,
  210. self::ROUND_FLOOR => true,
  211. self::ROUND_DOWN => true,
  212. self::ROUND_UP => true,
  213. );
  214. /**
  215. * The maximum value of the integer type in 32 bit platforms.
  216. *
  217. * @var int
  218. */
  219. private static $int32Max = 2147483647;
  220. /**
  221. * The maximum value of the integer type in 64 bit platforms.
  222. *
  223. * @var int|float
  224. */
  225. private static $int64Max = 9223372036854775807;
  226. private static $enSymbols = array(
  227. self::DECIMAL => array('.', ',', ';', '%', '0', '#', '-', '+', '¤', '¤¤', '.', 'E', '‰', '*', '∞', 'NaN', '@', ','),
  228. self::CURRENCY => array('.', ',', ';', '%', '0', '#', '-', '+', '¤', '¤¤', '.', 'E', '‰', '*', '∞', 'NaN', '@', ','),
  229. );
  230. private static $enTextAttributes = array(
  231. self::DECIMAL => array('', '', '-', '', ' ', '', ''),
  232. self::CURRENCY => array('¤', '', '-¤', '', ' ', ''),
  233. );
  234. /**
  235. * Constructor.
  236. *
  237. * @param string $locale The locale code. The only currently supported locale is "en" (or null using the default locale, i.e. "en")
  238. * @param int $style Style of the formatting, one of the format style constants
  239. * The only supported styles are NumberFormatter::DECIMAL
  240. * and NumberFormatter::CURRENCY.
  241. * @param string $pattern Not supported. A pattern string in case $style is NumberFormat::PATTERN_DECIMAL or
  242. * NumberFormat::PATTERN_RULEBASED. It must conform to the syntax
  243. * described in the ICU DecimalFormat or ICU RuleBasedNumberFormat documentation
  244. *
  245. * @see http://www.php.net/manual/en/numberformatter.create.php
  246. * @see http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details
  247. * @see http://www.icu-project.org/apiref/icu4c/classRuleBasedNumberFormat.html#_details
  248. *
  249. * @throws MethodArgumentValueNotImplementedException When $locale different than "en" or null is passed
  250. * @throws MethodArgumentValueNotImplementedException When the $style is not supported
  251. * @throws MethodArgumentNotImplementedException When the pattern value is different than null
  252. */
  253. public function __construct($locale = 'en', $style = null, $pattern = null)
  254. {
  255. if ('en' !== $locale && null !== $locale) {
  256. throw new MethodArgumentValueNotImplementedException(__METHOD__, 'locale', $locale, 'Only the locale "en" is supported');
  257. }
  258. if (!in_array($style, self::$supportedStyles)) {
  259. $message = sprintf('The available styles are: %s.', implode(', ', array_keys(self::$supportedStyles)));
  260. throw new MethodArgumentValueNotImplementedException(__METHOD__, 'style', $style, $message);
  261. }
  262. if (null !== $pattern) {
  263. throw new MethodArgumentNotImplementedException(__METHOD__, 'pattern');
  264. }
  265. $this->style = $style;
  266. }
  267. /**
  268. * Static constructor.
  269. *
  270. * @param string $locale The locale code. The only supported locale is "en" (or null using the default locale, i.e. "en")
  271. * @param int $style Style of the formatting, one of the format style constants
  272. * The only currently supported styles are NumberFormatter::DECIMAL
  273. * and NumberFormatter::CURRENCY.
  274. * @param string $pattern Not supported. A pattern string in case $style is NumberFormat::PATTERN_DECIMAL or
  275. * NumberFormat::PATTERN_RULEBASED. It must conform to the syntax
  276. * described in the ICU DecimalFormat or ICU RuleBasedNumberFormat documentation
  277. *
  278. * @return self
  279. *
  280. * @see http://www.php.net/manual/en/numberformatter.create.php
  281. * @see http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details
  282. * @see http://www.icu-project.org/apiref/icu4c/classRuleBasedNumberFormat.html#_details
  283. *
  284. * @throws MethodArgumentValueNotImplementedException When $locale different than "en" or null is passed
  285. * @throws MethodArgumentValueNotImplementedException When the $style is not supported
  286. * @throws MethodArgumentNotImplementedException When the pattern value is different than null
  287. */
  288. public static function create($locale = 'en', $style = null, $pattern = null)
  289. {
  290. return new self($locale, $style, $pattern);
  291. }
  292. /**
  293. * Format a currency value.
  294. *
  295. * @param float $value The numeric currency value
  296. * @param string $currency The 3-letter ISO 4217 currency code indicating the currency to use
  297. *
  298. * @return string The formatted currency value
  299. *
  300. * @see http://www.php.net/manual/en/numberformatter.formatcurrency.php
  301. * @see https://en.wikipedia.org/wiki/ISO_4217#Active_codes
  302. */
  303. public function formatCurrency($value, $currency)
  304. {
  305. if ($this->style == self::DECIMAL) {
  306. return $this->format($value);
  307. }
  308. $symbol = Intl::getCurrencyBundle()->getCurrencySymbol($currency, 'en');
  309. $fractionDigits = Intl::getCurrencyBundle()->getFractionDigits($currency);
  310. $value = $this->roundCurrency($value, $currency);
  311. $negative = false;
  312. if (0 > $value) {
  313. $negative = true;
  314. $value *= -1;
  315. }
  316. $value = $this->formatNumber($value, $fractionDigits);
  317. $ret = $symbol.$value;
  318. return $negative ? '-'.$ret : $ret;
  319. }
  320. /**
  321. * Format a number.
  322. *
  323. * @param number $value The value to format
  324. * @param int $type Type of the formatting, one of the format type constants
  325. * Only type NumberFormatter::TYPE_DEFAULT is currently supported.
  326. *
  327. * @return bool|string The formatted value or false on error
  328. *
  329. * @see http://www.php.net/manual/en/numberformatter.format.php
  330. *
  331. * @throws NotImplementedException If the method is called with the class $style 'CURRENCY'
  332. * @throws MethodArgumentValueNotImplementedException If the $type is different than TYPE_DEFAULT
  333. */
  334. public function format($value, $type = self::TYPE_DEFAULT)
  335. {
  336. // The original NumberFormatter does not support this format type
  337. if ($type == self::TYPE_CURRENCY) {
  338. trigger_error(__METHOD__.'(): Unsupported format type '.$type, \E_USER_WARNING);
  339. return false;
  340. }
  341. if ($this->style == self::CURRENCY) {
  342. throw new NotImplementedException(sprintf(
  343. '%s() method does not support the formatting of currencies (instance with CURRENCY style). %s',
  344. __METHOD__, NotImplementedException::INTL_INSTALL_MESSAGE
  345. ));
  346. }
  347. // Only the default type is supported.
  348. if ($type != self::TYPE_DEFAULT) {
  349. throw new MethodArgumentValueNotImplementedException(__METHOD__, 'type', $type, 'Only TYPE_DEFAULT is supported');
  350. }
  351. $fractionDigits = $this->getAttribute(self::FRACTION_DIGITS);
  352. $value = $this->round($value, $fractionDigits);
  353. $value = $this->formatNumber($value, $fractionDigits);
  354. // behave like the intl extension
  355. $this->resetError();
  356. return $value;
  357. }
  358. /**
  359. * Returns an attribute value.
  360. *
  361. * @param int $attr An attribute specifier, one of the numeric attribute constants
  362. *
  363. * @return bool|int The attribute value on success or false on error
  364. *
  365. * @see http://www.php.net/manual/en/numberformatter.getattribute.php
  366. */
  367. public function getAttribute($attr)
  368. {
  369. return isset($this->attributes[$attr]) ? $this->attributes[$attr] : null;
  370. }
  371. /**
  372. * Returns formatter's last error code. Always returns the U_ZERO_ERROR class constant value.
  373. *
  374. * @return int The error code from last formatter call
  375. *
  376. * @see http://www.php.net/manual/en/numberformatter.geterrorcode.php
  377. */
  378. public function getErrorCode()
  379. {
  380. return $this->errorCode;
  381. }
  382. /**
  383. * Returns formatter's last error message. Always returns the U_ZERO_ERROR_MESSAGE class constant value.
  384. *
  385. * @return string The error message from last formatter call
  386. *
  387. * @see http://www.php.net/manual/en/numberformatter.geterrormessage.php
  388. */
  389. public function getErrorMessage()
  390. {
  391. return $this->errorMessage;
  392. }
  393. /**
  394. * Returns the formatter's locale.
  395. *
  396. * The parameter $type is currently ignored.
  397. *
  398. * @param int $type Not supported. The locale name type to return (Locale::VALID_LOCALE or Locale::ACTUAL_LOCALE)
  399. *
  400. * @return string The locale used to create the formatter. Currently always
  401. * returns "en".
  402. *
  403. * @see http://www.php.net/manual/en/numberformatter.getlocale.php
  404. */
  405. public function getLocale($type = Locale::ACTUAL_LOCALE)
  406. {
  407. return 'en';
  408. }
  409. /**
  410. * Not supported. Returns the formatter's pattern.
  411. *
  412. * @return bool|string The pattern string used by the formatter or false on error
  413. *
  414. * @see http://www.php.net/manual/en/numberformatter.getpattern.php
  415. *
  416. * @throws MethodNotImplementedException
  417. */
  418. public function getPattern()
  419. {
  420. throw new MethodNotImplementedException(__METHOD__);
  421. }
  422. /**
  423. * Not supported. Returns a formatter symbol value.
  424. *
  425. * @param int $attr A symbol specifier, one of the format symbol constants
  426. *
  427. * @return bool|string The symbol value or false on error
  428. *
  429. * @see http://www.php.net/manual/en/numberformatter.getsymbol.php
  430. */
  431. public function getSymbol($attr)
  432. {
  433. return array_key_exists($this->style, self::$enSymbols) && array_key_exists($attr, self::$enSymbols[$this->style]) ? self::$enSymbols[$this->style][$attr] : false;
  434. }
  435. /**
  436. * Not supported. Returns a formatter text attribute value.
  437. *
  438. * @param int $attr An attribute specifier, one of the text attribute constants
  439. *
  440. * @return bool|string The attribute value or false on error
  441. *
  442. * @see http://www.php.net/manual/en/numberformatter.gettextattribute.php
  443. */
  444. public function getTextAttribute($attr)
  445. {
  446. return array_key_exists($this->style, self::$enTextAttributes) && array_key_exists($attr, self::$enTextAttributes[$this->style]) ? self::$enTextAttributes[$this->style][$attr] : false;
  447. }
  448. /**
  449. * Not supported. Parse a currency number.
  450. *
  451. * @param string $value The value to parse
  452. * @param string $currency Parameter to receive the currency name (reference)
  453. * @param int $position Offset to begin the parsing on return this value will hold the offset at which the parsing ended
  454. *
  455. * @return bool|string The parsed numeric value of false on error
  456. *
  457. * @see http://www.php.net/manual/en/numberformatter.parsecurrency.php
  458. *
  459. * @throws MethodNotImplementedException
  460. */
  461. public function parseCurrency($value, &$currency, &$position = null)
  462. {
  463. throw new MethodNotImplementedException(__METHOD__);
  464. }
  465. /**
  466. * Parse a number.
  467. *
  468. * @param string $value The value to parse
  469. * @param int $type Type of the formatting, one of the format type constants. NumberFormatter::TYPE_DOUBLE by default
  470. * @param int $position Offset to begin the parsing on return this value will hold the offset at which the parsing ended
  471. *
  472. * @return int|float|false The parsed value of false on error
  473. *
  474. * @see http://www.php.net/manual/en/numberformatter.parse.php
  475. */
  476. public function parse($value, $type = self::TYPE_DOUBLE, &$position = 0)
  477. {
  478. if ($type == self::TYPE_DEFAULT || $type == self::TYPE_CURRENCY) {
  479. trigger_error(__METHOD__.'(): Unsupported format type '.$type, \E_USER_WARNING);
  480. return false;
  481. }
  482. $groupSep = $this->getAttribute(self::GROUPING_USED) ? ',' : '';
  483. // Any string before the numeric value causes error in the parsing
  484. if (preg_match("/^-?(?:\.\d++|([\d{$groupSep}]++)(?:\.\d++)?)/", $value, $matches)) {
  485. $value = $matches[0];
  486. $position = strlen($value);
  487. if ($error = $groupSep && isset($matches[1]) && !preg_match('/^\d{1,3}+(?:(?:,\d{3})++|\d*+)$/', $matches[1])) {
  488. $position -= strlen(preg_replace('/^\d{1,3}+(?:(?:,\d++)++|\d*+)/', '', $matches[1]));
  489. }
  490. } else {
  491. $error = 1;
  492. $position = 0;
  493. }
  494. if ($error) {
  495. IntlGlobals::setError(IntlGlobals::U_PARSE_ERROR, 'Number parsing failed');
  496. $this->errorCode = IntlGlobals::getErrorCode();
  497. $this->errorMessage = IntlGlobals::getErrorMessage();
  498. return false;
  499. }
  500. $value = str_replace(',', '', $value);
  501. $value = $this->convertValueDataType($value, $type);
  502. // behave like the intl extension
  503. $this->resetError();
  504. return $value;
  505. }
  506. /**
  507. * Set an attribute.
  508. *
  509. * @param int $attr An attribute specifier, one of the numeric attribute constants
  510. * The only currently supported attributes are NumberFormatter::FRACTION_DIGITS,
  511. * NumberFormatter::GROUPING_USED and NumberFormatter::ROUNDING_MODE.
  512. * @param int $value The attribute value
  513. *
  514. * @return bool true on success or false on failure
  515. *
  516. * @see http://www.php.net/manual/en/numberformatter.setattribute.php
  517. *
  518. * @throws MethodArgumentValueNotImplementedException When the $attr is not supported
  519. * @throws MethodArgumentValueNotImplementedException When the $value is not supported
  520. */
  521. public function setAttribute($attr, $value)
  522. {
  523. if (!in_array($attr, self::$supportedAttributes)) {
  524. $message = sprintf(
  525. 'The available attributes are: %s',
  526. implode(', ', array_keys(self::$supportedAttributes))
  527. );
  528. throw new MethodArgumentValueNotImplementedException(__METHOD__, 'attr', $value, $message);
  529. }
  530. if (self::$supportedAttributes['ROUNDING_MODE'] == $attr && $this->isInvalidRoundingMode($value)) {
  531. $message = sprintf(
  532. 'The supported values for ROUNDING_MODE are: %s',
  533. implode(', ', array_keys(self::$roundingModes))
  534. );
  535. throw new MethodArgumentValueNotImplementedException(__METHOD__, 'attr', $value, $message);
  536. }
  537. if (self::$supportedAttributes['GROUPING_USED'] == $attr) {
  538. $value = $this->normalizeGroupingUsedValue($value);
  539. }
  540. if (self::$supportedAttributes['FRACTION_DIGITS'] == $attr) {
  541. $value = $this->normalizeFractionDigitsValue($value);
  542. }
  543. $this->attributes[$attr] = $value;
  544. $this->initializedAttributes[$attr] = true;
  545. return true;
  546. }
  547. /**
  548. * Not supported. Set the formatter's pattern.
  549. *
  550. * @param string $pattern A pattern string in conformance with the ICU DecimalFormat documentation
  551. *
  552. * @return bool true on success or false on failure
  553. *
  554. * @see http://www.php.net/manual/en/numberformatter.setpattern.php
  555. * @see http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details
  556. *
  557. * @throws MethodNotImplementedException
  558. */
  559. public function setPattern($pattern)
  560. {
  561. throw new MethodNotImplementedException(__METHOD__);
  562. }
  563. /**
  564. * Not supported. Set the formatter's symbol.
  565. *
  566. * @param int $attr A symbol specifier, one of the format symbol constants
  567. * @param string $value The value for the symbol
  568. *
  569. * @return bool true on success or false on failure
  570. *
  571. * @see http://www.php.net/manual/en/numberformatter.setsymbol.php
  572. *
  573. * @throws MethodNotImplementedException
  574. */
  575. public function setSymbol($attr, $value)
  576. {
  577. throw new MethodNotImplementedException(__METHOD__);
  578. }
  579. /**
  580. * Not supported. Set a text attribute.
  581. *
  582. * @param int $attr An attribute specifier, one of the text attribute constants
  583. * @param int $value The attribute value
  584. *
  585. * @return bool true on success or false on failure
  586. *
  587. * @see http://www.php.net/manual/en/numberformatter.settextattribute.php
  588. *
  589. * @throws MethodNotImplementedException
  590. */
  591. public function setTextAttribute($attr, $value)
  592. {
  593. throw new MethodNotImplementedException(__METHOD__);
  594. }
  595. /**
  596. * Set the error to the default U_ZERO_ERROR.
  597. */
  598. protected function resetError()
  599. {
  600. IntlGlobals::setError(IntlGlobals::U_ZERO_ERROR);
  601. $this->errorCode = IntlGlobals::getErrorCode();
  602. $this->errorMessage = IntlGlobals::getErrorMessage();
  603. }
  604. /**
  605. * Rounds a currency value, applying increment rounding if applicable.
  606. *
  607. * When a currency have a rounding increment, an extra round is made after the first one. The rounding factor is
  608. * determined in the ICU data and is explained as of:
  609. *
  610. * "the rounding increment is given in units of 10^(-fraction_digits)"
  611. *
  612. * The only actual rounding data as of this writing, is CHF.
  613. *
  614. * @param float $value The numeric currency value
  615. * @param string $currency The 3-letter ISO 4217 currency code indicating the currency to use
  616. *
  617. * @return float The rounded numeric currency value
  618. *
  619. * @see http://en.wikipedia.org/wiki/Swedish_rounding
  620. * @see http://www.docjar.com/html/api/com/ibm/icu/util/Currency.java.html#1007
  621. */
  622. private function roundCurrency($value, $currency)
  623. {
  624. $fractionDigits = Intl::getCurrencyBundle()->getFractionDigits($currency);
  625. $roundingIncrement = Intl::getCurrencyBundle()->getRoundingIncrement($currency);
  626. // Round with the formatter rounding mode
  627. $value = $this->round($value, $fractionDigits);
  628. // Swiss rounding
  629. if (0 < $roundingIncrement && 0 < $fractionDigits) {
  630. $roundingFactor = $roundingIncrement / pow(10, $fractionDigits);
  631. $value = round($value / $roundingFactor) * $roundingFactor;
  632. }
  633. return $value;
  634. }
  635. /**
  636. * Rounds a value.
  637. *
  638. * @param int|float $value The value to round
  639. * @param int $precision The number of decimal digits to round to
  640. *
  641. * @return int|float The rounded value
  642. */
  643. private function round($value, $precision)
  644. {
  645. $precision = $this->getUninitializedPrecision($value, $precision);
  646. $roundingModeAttribute = $this->getAttribute(self::ROUNDING_MODE);
  647. if (isset(self::$phpRoundingMap[$roundingModeAttribute])) {
  648. $value = round($value, $precision, self::$phpRoundingMap[$roundingModeAttribute]);
  649. } elseif (isset(self::$customRoundingList[$roundingModeAttribute])) {
  650. $roundingCoef = pow(10, $precision);
  651. $value *= $roundingCoef;
  652. switch ($roundingModeAttribute) {
  653. case self::ROUND_CEILING:
  654. $value = ceil($value);
  655. break;
  656. case self::ROUND_FLOOR:
  657. $value = floor($value);
  658. break;
  659. case self::ROUND_UP:
  660. $value = $value > 0 ? ceil($value) : floor($value);
  661. break;
  662. case self::ROUND_DOWN:
  663. $value = $value > 0 ? floor($value) : ceil($value);
  664. break;
  665. }
  666. $value /= $roundingCoef;
  667. }
  668. return $value;
  669. }
  670. /**
  671. * Formats a number.
  672. *
  673. * @param int|float $value The numeric value to format
  674. * @param int $precision The number of decimal digits to use
  675. *
  676. * @return string The formatted number
  677. */
  678. private function formatNumber($value, $precision)
  679. {
  680. $precision = $this->getUninitializedPrecision($value, $precision);
  681. return number_format($value, $precision, '.', $this->getAttribute(self::GROUPING_USED) ? ',' : '');
  682. }
  683. /**
  684. * Returns the precision value if the DECIMAL style is being used and the FRACTION_DIGITS attribute is uninitialized.
  685. *
  686. * @param int|float $value The value to get the precision from if the FRACTION_DIGITS attribute is uninitialized
  687. * @param int $precision The precision value to returns if the FRACTION_DIGITS attribute is initialized
  688. *
  689. * @return int The precision value
  690. */
  691. private function getUninitializedPrecision($value, $precision)
  692. {
  693. if ($this->style == self::CURRENCY) {
  694. return $precision;
  695. }
  696. if (!$this->isInitializedAttribute(self::FRACTION_DIGITS)) {
  697. preg_match('/.*\.(.*)/', (string) $value, $digits);
  698. if (isset($digits[1])) {
  699. $precision = strlen($digits[1]);
  700. }
  701. }
  702. return $precision;
  703. }
  704. /**
  705. * Check if the attribute is initialized (value set by client code).
  706. *
  707. * @param string $attr The attribute name
  708. *
  709. * @return bool true if the value was set by client, false otherwise
  710. */
  711. private function isInitializedAttribute($attr)
  712. {
  713. return isset($this->initializedAttributes[$attr]);
  714. }
  715. /**
  716. * Returns the numeric value using the $type to convert to the right data type.
  717. *
  718. * @param mixed $value The value to be converted
  719. * @param int $type The type to convert. Can be TYPE_DOUBLE (float) or TYPE_INT32 (int)
  720. *
  721. * @return int|float|false The converted value
  722. */
  723. private function convertValueDataType($value, $type)
  724. {
  725. if ($type == self::TYPE_DOUBLE) {
  726. $value = (float) $value;
  727. } elseif ($type == self::TYPE_INT32) {
  728. $value = $this->getInt32Value($value);
  729. } elseif ($type == self::TYPE_INT64) {
  730. $value = $this->getInt64Value($value);
  731. }
  732. return $value;
  733. }
  734. /**
  735. * Convert the value data type to int or returns false if the value is out of the integer value range.
  736. *
  737. * @param mixed $value The value to be converted
  738. *
  739. * @return int|false The converted value
  740. */
  741. private function getInt32Value($value)
  742. {
  743. if ($value > self::$int32Max || $value < -self::$int32Max - 1) {
  744. return false;
  745. }
  746. return (int) $value;
  747. }
  748. /**
  749. * Convert the value data type to int or returns false if the value is out of the integer value range.
  750. *
  751. * @param mixed $value The value to be converted
  752. *
  753. * @return int|float|false The converted value
  754. */
  755. private function getInt64Value($value)
  756. {
  757. if ($value > self::$int64Max || $value < -self::$int64Max - 1) {
  758. return false;
  759. }
  760. if (PHP_INT_SIZE !== 8 && ($value > self::$int32Max || $value < -self::$int32Max - 1)) {
  761. return (float) $value;
  762. }
  763. return (int) $value;
  764. }
  765. /**
  766. * Check if the rounding mode is invalid.
  767. *
  768. * @param int $value The rounding mode value to check
  769. *
  770. * @return bool true if the rounding mode is invalid, false otherwise
  771. */
  772. private function isInvalidRoundingMode($value)
  773. {
  774. if (in_array($value, self::$roundingModes, true)) {
  775. return false;
  776. }
  777. return true;
  778. }
  779. /**
  780. * Returns the normalized value for the GROUPING_USED attribute. Any value that can be converted to int will be
  781. * cast to Boolean and then to int again. This way, negative values are converted to 1 and string values to 0.
  782. *
  783. * @param mixed $value The value to be normalized
  784. *
  785. * @return int The normalized value for the attribute (0 or 1)
  786. */
  787. private function normalizeGroupingUsedValue($value)
  788. {
  789. return (int) (bool) (int) $value;
  790. }
  791. /**
  792. * Returns the normalized value for the FRACTION_DIGITS attribute. The value is converted to int and if negative,
  793. * the returned value will be 0.
  794. *
  795. * @param mixed $value The value to be normalized
  796. *
  797. * @return int The normalized value for the attribute
  798. */
  799. private function normalizeFractionDigitsValue($value)
  800. {
  801. $value = (int) $value;
  802. return (0 > $value) ? 0 : $value;
  803. }
  804. }