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