ByteValidator::format()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 1
nop 2
crap 2
1
<?php
2
/**
3
 * Byte values validator
4
 *
5
 * @file      ByteValidator.php
6
 *
7
 * PHP version 8.0+
8
 *
9
 * @author    Alexander Yancharuk <alex at itvault dot info>
10
 * @copyright © 2012-2021 Alexander Yancharuk
11
 * @date      Вск Фев 17 10:48:43 2013
12
 * @license   The BSD 3-Clause License
13
 *            <https://tldrlegal.com/license/bsd-3-clause-license-(revised)>
14
 */
15
16
namespace Veles\Validators;
17
18
/**
19
 * Class ByteValidator
20
 * @author  Alexander Yancharuk <alex at itvault dot info>
21
 */
22
class ByteValidator implements ValidatorInterface
23
{
24
	/**
25
	 * Check byte values
26
	 *
27
	 * @param mixed $size Size in bytes
28
	 * @return bool
29
	 */
30 6
	public function check($size)
31
	{
32 6
		return is_numeric($size);
33
	}
34
35
	/**
36
	 * Convert byte values to human readable format
37
	 *
38
	 * @param int $size Size in bytes
39
	 * @param int $precision Precision of returned values
40
	 * @return string
41
	 */
42 6
	public static function format($size, $precision = 2)
43
	{
44 6
		$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
45
46 6
		$size = max($size, 0);
47 6
		$pow = floor(($size ? log($size) : 0) / log(1024));
48 6
		$pow = min($pow, count($units) - 1);
49
50 6
		$size /= (1 << (10 * $pow));
51
52 6
		return number_format($size, $precision) . ' ' . $units[$pow];
53
	}
54
}
55