PageRenderTime 54ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Utility/CakeNumber.php

https://gitlab.com/manuperazafa/elsartenbackend
PHP | 416 lines | 202 code | 32 blank | 182 comment | 35 complexity | 9559f58bd2ffabc164aaf77859653375 MD5 | raw file
  1. <?php
  2. /**
  3. * CakeNumber Utility.
  4. *
  5. * Methods to make numbers more readable.
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * For full copyright and license information, please see the LICENSE.txt
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @package Cake.Utility
  17. * @since CakePHP(tm) v 0.10.0.1076
  18. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  19. */
  20. /**
  21. * Number helper library.
  22. *
  23. * Methods to make numbers more readable.
  24. *
  25. * @package Cake.Utility
  26. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html
  27. */
  28. class CakeNumber {
  29. /**
  30. * Currencies supported by the helper. You can add additional currency formats
  31. * with CakeNumber::addFormat
  32. *
  33. * @var array
  34. */
  35. protected static $_currencies = array(
  36. 'AUD' => array(
  37. 'wholeSymbol' => '$', 'wholePosition' => 'before', 'fractionSymbol' => 'c', 'fractionPosition' => 'after',
  38. 'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
  39. 'fractionExponent' => 2
  40. ),
  41. 'CAD' => array(
  42. 'wholeSymbol' => '$', 'wholePosition' => 'before', 'fractionSymbol' => 'c', 'fractionPosition' => 'after',
  43. 'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
  44. 'fractionExponent' => 2
  45. ),
  46. 'USD' => array(
  47. 'wholeSymbol' => '$', 'wholePosition' => 'before', 'fractionSymbol' => 'c', 'fractionPosition' => 'after',
  48. 'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
  49. 'fractionExponent' => 2
  50. ),
  51. 'EUR' => array(
  52. 'wholeSymbol' => '€', 'wholePosition' => 'before', 'fractionSymbol' => false, 'fractionPosition' => 'after',
  53. 'zero' => 0, 'places' => 2, 'thousands' => '.', 'decimals' => ',', 'negative' => '()', 'escape' => true,
  54. 'fractionExponent' => 0
  55. ),
  56. 'GBP' => array(
  57. 'wholeSymbol' => '£', 'wholePosition' => 'before', 'fractionSymbol' => 'p', 'fractionPosition' => 'after',
  58. 'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
  59. 'fractionExponent' => 2
  60. ),
  61. 'JPY' => array(
  62. 'wholeSymbol' => '¥', 'wholePosition' => 'before', 'fractionSymbol' => false, 'fractionPosition' => 'after',
  63. 'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
  64. 'fractionExponent' => 0
  65. ),
  66. );
  67. /**
  68. * Default options for currency formats
  69. *
  70. * @var array
  71. */
  72. protected static $_currencyDefaults = array(
  73. 'wholeSymbol' => '', 'wholePosition' => 'before', 'fractionSymbol' => false, 'fractionPosition' => 'after',
  74. 'zero' => '0', 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
  75. 'fractionExponent' => 2
  76. );
  77. /**
  78. * Default currency used by CakeNumber::currency()
  79. *
  80. * @var string
  81. */
  82. protected static $_defaultCurrency = 'USD';
  83. /**
  84. * If native number_format() should be used. If >= PHP5.4
  85. *
  86. * @var bool
  87. */
  88. protected static $_numberFormatSupport = null;
  89. /**
  90. * Formats a number with a level of precision.
  91. *
  92. * @param float $value A floating point number.
  93. * @param int $precision The precision of the returned number.
  94. * @return float Formatted float.
  95. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::precision
  96. */
  97. public static function precision($value, $precision = 3) {
  98. return sprintf("%01.{$precision}f", $value);
  99. }
  100. /**
  101. * Returns a formatted-for-humans file size.
  102. *
  103. * @param int $size Size in bytes
  104. * @return string Human readable size
  105. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toReadableSize
  106. */
  107. public static function toReadableSize($size) {
  108. switch (true) {
  109. case $size < 1024:
  110. return __dn('cake', '%d Byte', '%d Bytes', $size, $size);
  111. case round($size / 1024) < 1024:
  112. return __d('cake', '%s KB', self::precision($size / 1024, 0));
  113. case round($size / 1024 / 1024, 2) < 1024:
  114. return __d('cake', '%s MB', self::precision($size / 1024 / 1024, 2));
  115. case round($size / 1024 / 1024 / 1024, 2) < 1024:
  116. return __d('cake', '%s GB', self::precision($size / 1024 / 1024 / 1024, 2));
  117. default:
  118. return __d('cake', '%s TB', self::precision($size / 1024 / 1024 / 1024 / 1024, 2));
  119. }
  120. }
  121. /**
  122. * Converts filesize from human readable string to bytes
  123. *
  124. * @param string $size Size in human readable string like '5MB', '5M', '500B', '50kb' etc.
  125. * @param mixed $default Value to be returned when invalid size was used, for example 'Unknown type'
  126. * @return mixed Number of bytes as integer on success, `$default` on failure if not false
  127. * @throws CakeException On invalid Unit type.
  128. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::fromReadableSize
  129. */
  130. public static function fromReadableSize($size, $default = false) {
  131. if (ctype_digit($size)) {
  132. return (int)$size;
  133. }
  134. $size = strtoupper($size);
  135. $l = -2;
  136. $i = array_search(substr($size, -2), array('KB', 'MB', 'GB', 'TB', 'PB'));
  137. if ($i === false) {
  138. $l = -1;
  139. $i = array_search(substr($size, -1), array('K', 'M', 'G', 'T', 'P'));
  140. }
  141. if ($i !== false) {
  142. $size = substr($size, 0, $l);
  143. return $size * pow(1024, $i + 1);
  144. }
  145. if (substr($size, -1) === 'B' && ctype_digit(substr($size, 0, -1))) {
  146. $size = substr($size, 0, -1);
  147. return (int)$size;
  148. }
  149. if ($default !== false) {
  150. return $default;
  151. }
  152. throw new CakeException(__d('cake_dev', 'No unit type.'));
  153. }
  154. /**
  155. * Formats a number into a percentage string.
  156. *
  157. * Options:
  158. *
  159. * - `multiply`: Multiply the input value by 100 for decimal percentages.
  160. *
  161. * @param float $value A floating point number
  162. * @param int $precision The precision of the returned number
  163. * @param array $options Options
  164. * @return string Percentage string
  165. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toPercentage
  166. */
  167. public static function toPercentage($value, $precision = 2, $options = array()) {
  168. $options += array('multiply' => false);
  169. if ($options['multiply']) {
  170. $value *= 100;
  171. }
  172. return self::precision($value, $precision) . '%';
  173. }
  174. /**
  175. * Formats a number into a currency format.
  176. *
  177. * @param float $value A floating point number
  178. * @param int $options If integer then places, if string then before, if (,.-) then use it
  179. * or array with places and before keys
  180. * @return string formatted number
  181. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::format
  182. */
  183. public static function format($value, $options = false) {
  184. $places = 0;
  185. if (is_int($options)) {
  186. $places = $options;
  187. }
  188. $separators = array(',', '.', '-', ':');
  189. $before = $after = null;
  190. if (is_string($options) && !in_array($options, $separators)) {
  191. $before = $options;
  192. }
  193. $thousands = ',';
  194. if (!is_array($options) && in_array($options, $separators)) {
  195. $thousands = $options;
  196. }
  197. $decimals = '.';
  198. if (!is_array($options) && in_array($options, $separators)) {
  199. $decimals = $options;
  200. }
  201. $escape = true;
  202. if (is_array($options)) {
  203. $defaults = array('before' => '$', 'places' => 2, 'thousands' => ',', 'decimals' => '.');
  204. $options += $defaults;
  205. extract($options);
  206. }
  207. $value = self::_numberFormat($value, $places, '.', '');
  208. $out = $before . self::_numberFormat($value, $places, $decimals, $thousands) . $after;
  209. if ($escape) {
  210. return h($out);
  211. }
  212. return $out;
  213. }
  214. /**
  215. * Formats a number into a currency format to show deltas (signed differences in value).
  216. *
  217. * ### Options
  218. *
  219. * - `places` - Number of decimal places to use. ie. 2
  220. * - `fractionExponent` - Fraction exponent of this specific currency. Defaults to 2.
  221. * - `before` - The string to place before whole numbers. ie. '['
  222. * - `after` - The string to place after decimal numbers. ie. ']'
  223. * - `thousands` - Thousands separator ie. ','
  224. * - `decimals` - Decimal separator symbol ie. '.'
  225. *
  226. * @param float $value A floating point number
  227. * @param array $options Options list.
  228. * @return string formatted delta
  229. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::formatDelta
  230. */
  231. public static function formatDelta($value, $options = array()) {
  232. $places = isset($options['places']) ? $options['places'] : 0;
  233. $value = self::_numberFormat($value, $places, '.', '');
  234. $sign = $value > 0 ? '+' : '';
  235. $options['before'] = isset($options['before']) ? $options['before'] . $sign : $sign;
  236. return self::format($value, $options);
  237. }
  238. /**
  239. * Alternative number_format() to accommodate multibyte decimals and thousands < PHP 5.4
  240. *
  241. * @param float $value Value to format.
  242. * @param int $places Decimal places to use.
  243. * @param string $decimals Decimal position string.
  244. * @param string $thousands Thousands separator string.
  245. * @return string
  246. */
  247. protected static function _numberFormat($value, $places = 0, $decimals = '.', $thousands = ',') {
  248. if (!isset(self::$_numberFormatSupport)) {
  249. self::$_numberFormatSupport = version_compare(PHP_VERSION, '5.4.0', '>=');
  250. }
  251. if (self::$_numberFormatSupport) {
  252. return number_format($value, $places, $decimals, $thousands);
  253. }
  254. $value = number_format($value, $places, '.', '');
  255. $after = '';
  256. $foundDecimal = strpos($value, '.');
  257. if ($foundDecimal !== false) {
  258. $after = substr($value, $foundDecimal);
  259. $value = substr($value, 0, $foundDecimal);
  260. }
  261. while (($foundThousand = preg_replace('/(\d+)(\d\d\d)/', '\1 \2', $value)) !== $value) {
  262. $value = $foundThousand;
  263. }
  264. $value .= $after;
  265. return strtr($value, array(' ' => $thousands, '.' => $decimals));
  266. }
  267. /**
  268. * Formats a number into a currency format.
  269. *
  270. * ### Options
  271. *
  272. * - `wholeSymbol` - The currency symbol to use for whole numbers,
  273. * greater than 1, or less than -1.
  274. * - `wholePosition` - The position the whole symbol should be placed
  275. * valid options are 'before' & 'after'.
  276. * - `fractionSymbol` - The currency symbol to use for fractional numbers.
  277. * - `fractionPosition` - The position the fraction symbol should be placed
  278. * valid options are 'before' & 'after'.
  279. * - `before` - The currency symbol to place before whole numbers
  280. * ie. '$'. `before` is an alias for `wholeSymbol`.
  281. * - `after` - The currency symbol to place after decimal numbers
  282. * ie. 'c'. Set to boolean false to use no decimal symbol.
  283. * eg. 0.35 => $0.35. `after` is an alias for `fractionSymbol`
  284. * - `zero` - The text to use for zero values, can be a
  285. * string or a number. ie. 0, 'Free!'
  286. * - `places` - Number of decimal places to use. ie. 2
  287. * - `fractionExponent` - Fraction exponent of this specific currency. Defaults to 2.
  288. * - `thousands` - Thousands separator ie. ','
  289. * - `decimals` - Decimal separator symbol ie. '.'
  290. * - `negative` - Symbol for negative numbers. If equal to '()',
  291. * the number will be wrapped with ( and )
  292. * - `escape` - Should the output be escaped for html special characters.
  293. * The default value for this option is controlled by the currency settings.
  294. * By default all currencies contain utf-8 symbols and don't need this changed. If you require
  295. * non HTML encoded symbols you will need to update the settings with the correct bytes.
  296. *
  297. * @param float $value Value to format.
  298. * @param string $currency Shortcut to default options. Valid values are
  299. * 'USD', 'EUR', 'GBP', otherwise set at least 'before' and 'after' options.
  300. * @param array $options Options list.
  301. * @return string Number formatted as a currency.
  302. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::currency
  303. */
  304. public static function currency($value, $currency = null, $options = array()) {
  305. $defaults = self::$_currencyDefaults;
  306. if ($currency === null) {
  307. $currency = self::defaultCurrency();
  308. }
  309. if (isset(self::$_currencies[$currency])) {
  310. $defaults = self::$_currencies[$currency];
  311. } elseif (is_string($currency)) {
  312. $options['before'] = $currency;
  313. }
  314. $options += $defaults;
  315. if (isset($options['before']) && $options['before'] !== '') {
  316. $options['wholeSymbol'] = $options['before'];
  317. }
  318. if (isset($options['after']) && !$options['after'] !== '') {
  319. $options['fractionSymbol'] = $options['after'];
  320. }
  321. $result = $options['before'] = $options['after'] = null;
  322. $symbolKey = 'whole';
  323. $value = (float)$value;
  324. if (!$value) {
  325. if ($options['zero'] !== 0) {
  326. return $options['zero'];
  327. }
  328. } elseif ($value < 1 && $value > -1) {
  329. if ($options['fractionSymbol'] !== false) {
  330. $multiply = pow(10, $options['fractionExponent']);
  331. $value = $value * $multiply;
  332. $options['places'] = null;
  333. $symbolKey = 'fraction';
  334. }
  335. }
  336. $position = $options[$symbolKey . 'Position'] !== 'after' ? 'before' : 'after';
  337. $options[$position] = $options[$symbolKey . 'Symbol'];
  338. $abs = abs($value);
  339. $result = self::format($abs, $options);
  340. if ($value < 0) {
  341. if ($options['negative'] === '()') {
  342. $result = '(' . $result . ')';
  343. } else {
  344. $result = $options['negative'] . $result;
  345. }
  346. }
  347. return $result;
  348. }
  349. /**
  350. * Add a currency format to the Number helper. Makes reusing
  351. * currency formats easier.
  352. *
  353. * {{{ $number->addFormat('NOK', array('before' => 'Kr. ')); }}}
  354. *
  355. * You can now use `NOK` as a shortform when formatting currency amounts.
  356. *
  357. * {{{ $number->currency($value, 'NOK'); }}}
  358. *
  359. * Added formats are merged with the defaults defined in CakeNumber::$_currencyDefaults
  360. * See CakeNumber::currency() for more information on the various options and their function.
  361. *
  362. * @param string $formatName The format name to be used in the future.
  363. * @param array $options The array of options for this format.
  364. * @return void
  365. * @see NumberHelper::currency()
  366. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::addFormat
  367. */
  368. public static function addFormat($formatName, $options) {
  369. self::$_currencies[$formatName] = $options + self::$_currencyDefaults;
  370. }
  371. /**
  372. * Getter/setter for default currency
  373. *
  374. * @param string $currency Default currency string used by currency() if $currency argument is not provided
  375. * @return string Currency
  376. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::defaultCurrency
  377. */
  378. public static function defaultCurrency($currency = null) {
  379. if ($currency) {
  380. self::$_defaultCurrency = $currency;
  381. }
  382. return self::$_defaultCurrency;
  383. }
  384. }