1: <?php
2: /**
3: * Copyright 2007 Maintainable Software, LLC
4: * Copyright 2006-2012 Horde LLC (http://www.horde.org/)
5: *
6: * @author Mike Naberezny <mike@maintainable.com>
7: * @author Derek DeVries <derek@maintainable.com>
8: * @author Chuck Hagenbuch <chuck@horde.org>
9: * @license http://www.horde.org/licenses/bsd
10: * @category Horde
11: * @package View
12: * @subpackage Helper
13: */
14:
15: /**
16: * View helpers for numbers.
17: *
18: * @author Mike Naberezny <mike@maintainable.com>
19: * @author Derek DeVries <derek@maintainable.com>
20: * @author Chuck Hagenbuch <chuck@horde.org>
21: * @license http://www.horde.org/licenses/bsd
22: * @category Horde
23: * @package View
24: * @subpackage Helper
25: */
26: class Horde_View_Helper_Number extends Horde_View_Helper_Base
27: {
28: /**
29: * Formats the bytes in $size into a more understandable representation.
30: *
31: * Useful for reporting file sizes to users. This method returns NULL if
32: * $size cannot be converted into a number. You can change the default
33: * precision of 1 in $precision.
34: *
35: * <pre>
36: * $this->numberToHumanSize(123) => 123 Bytes
37: * $this->numberToHumanSize(1234) => 1.2 KB
38: * $this->numberToHumanSize(12345) => 12.1 KB
39: * $this->numberToHumanSize(1234567) => 1.2 MB
40: * $this->numberToHumanSize(1234567890) => 1.1 GB
41: * $this->numberToHumanSize(1234567890123) => 1.1 TB
42: * $this->numberToHumanSize(1234567, 2) => 1.18 MB
43: * </pre>
44: *
45: * @param integer|float $size Size to format.
46: * @param integer $preceision Level of precision.
47: *
48: * @return string Formatted size value.
49: */
50: public function numberToHumanSize($size, $precision = 1)
51: {
52: if (!is_numeric($size)) {
53: return null;
54: }
55:
56: if ($size == 1) {
57: $size = '1 Byte';
58: } elseif ($size < 1024) {
59: $size = sprintf('%d Bytes', $size);
60: } elseif ($size < 1048576) {
61: $size = sprintf("%.{$precision}f KB", $size / 1024);
62: } elseif ($size < 1073741824) {
63: $size = sprintf("%.{$precision}f MB", $size / 1048576);
64: } elseif ($size < 1099511627776) {
65: $size = sprintf("%.{$precision}f GB", $size / 1073741824);
66: } else {
67: $size = sprintf("%.{$precision}f TB", $size / 1099511627776);
68: }
69:
70: return str_replace('.0', '', $size);
71: }
72: }
73: