PageRenderTime 27ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Utility/CakeNumber.php

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