Merge pull request #7174 from kinglozzer/memstring2bytes

Update Convert::memstring2bytes() logic
This commit is contained in:
Loz Calver 2017-07-14 09:57:57 +01:00 committed by GitHub
commit c96faa3043
2 changed files with 68 additions and 14 deletions

View File

@ -551,8 +551,6 @@ class Convert
return $return;
}
/**
* Turn a memory string, such as 512M into an actual number of bytes.
*
@ -561,18 +559,18 @@ class Convert
*/
public static function memstring2bytes($memString)
{
switch (strtolower(substr($memString, -1))) {
case "b":
return round(substr($memString, 0, -1));
case "k":
return round(substr($memString, 0, -1) * 1024);
case "m":
return round(substr($memString, 0, -1) * 1024 * 1024);
case "g":
return round(substr($memString, 0, -1) * 1024 * 1024 * 1024);
default:
return round($memString);
// Remove non-unit characters from the size
$unit = preg_replace('/[^bkmgtpezy]/i', '', $memString);
// Remove non-numeric characters from the size
$size = preg_replace('/[^0-9\.]/', '', $memString);
if ($unit) {
// Find the position of the unit in the ordered string which is the power
// of magnitude to multiply a kilobyte by
return round($size * pow(1024, stripos('bkmgtpezy', $unit[0])));
}
return round($size);
}
/**
@ -582,7 +580,7 @@ class Convert
*/
public static function bytes2memstring($bytes, $decimal = 0)
{
$scales = ['B','K','M','G'];
$scales = ['B','K','M','G','T','P','E','Z','Y'];
// Get scale
$scale = (int)floor(log($bytes, 1024));
if (!isset($scales[$scale])) {

View File

@ -517,4 +517,60 @@ XML
'Non-alpha leading with trailing upper camel'
);
}
/**
* Test that memstring2bytes returns the number of bytes for a PHP ini style size declaration
*
* @param string $memString
* @param int $expected
* @dataProvider memString2BytesProvider
*/
public function testMemString2Bytes($memString, $expected)
{
$this->assertSame($expected, Convert::memstring2bytes($memString));
}
/**
* @return array
*/
public function memString2BytesProvider()
{
return [
['2048', (float)(2 * 1024)],
['2k', (float)(2 * 1024)],
['512M', (float)(512 * 1024 * 1024)],
['512MiB', (float)(512 * 1024 * 1024)],
['512 mbytes', (float)(512 * 1024 * 1024)],
['512 megabytes', (float)(512 * 1024 * 1024)],
['1024g', (float)(1024 * 1024 * 1024 * 1024)],
['1024G', (float)(1024 * 1024 * 1024 * 1024)]
];
}
/**
* Test that bytes2memstring returns a binary prefixed string representing the number of bytes
*
* @param string $memString
* @param int $expected
* @dataProvider bytes2MemStringProvider
*/
public function testBytes2MemString($bytes, $expected)
{
$this->assertSame($expected, Convert::bytes2memstring($bytes));
}
/**
* @return array
*/
public function bytes2MemStringProvider()
{
return [
[200, '200B'],
[(2 * 1024), '2K'],
[(512 * 1024 * 1024), '512M'],
[(512 * 1024 * 1024 * 1024), '512G'],
[(512 * 1024 * 1024 * 1024 * 1024), '512T'],
[(512 * 1024 * 1024 * 1024 * 1024 * 1024), '512P']
];
}
}