Merge pull request #7153 from kinglozzer/file-ini2bytes

Fix: Make File::ini2bytes() compliant with binary prefixes (fixes #7145)
This commit is contained in:
Damian Mooyman 2017-07-11 11:29:05 +12:00 committed by GitHub
commit 10fd7813ed
2 changed files with 41 additions and 17 deletions

View File

@ -887,24 +887,21 @@ class File extends DataObject {
* @return int
*/
public static function ini2bytes($iniValue) {
$iniValues = str_split(trim($iniValue));
$unit = strtolower(array_pop($iniValues));
$quantity = (int) implode($iniValues);
switch ($unit) {
case 'g':
$quantity *= 1024;
// deliberate no break
case 'm':
$quantity *= 1024;
// deliberate no break
case 'k':
$quantity *= 1024;
// deliberate no break
default:
// no-op: pre-existing behaviour
break;
// Remove non-unit characters from the size
$unit = preg_replace('/[^bkmgtpezy]/i', '', $iniValue);
// Remove non-numeric characters from the size
$size = preg_replace('/[^0-9\.]/', '', $iniValue);
if ($unit) {
// Find the position of the unit in the ordered string which is the power
// of magnitude to multiply a kilobyte by
$size = round($size * pow(1024, stripos('bkmgtpezy', $unit[0])));
} else {
$size = round($size);
}
return $quantity;
// Cast to int - round() returns a float
return (int)$size;
}
/**

View File

@ -413,6 +413,33 @@ class FileTest extends SapphireTest {
$this->assertTrue($file->canEdit(), "Admins can edit files");
}
/**
* Test that ini2bytes returns the number of bytes for a PHP ini style size declaration
*
* @param string $iniValue
* @param int $expected
* @dataProvider ini2BytesProvider
*/
public function testIni2Bytes($iniValue, $expected) {
$this->assertSame($expected, File::ini2bytes($iniValue));
}
/**
* @return array
*/
public function ini2BytesProvider() {
return array(
array('2048', 2 * 1024),
array('2k', 2 * 1024),
array('512M', 512 * 1024 * 1024),
array('512MiB', 512 * 1024 * 1024),
array('512 mbytes', 512 * 1024 * 1024),
array('512 megabytes', 512 * 1024 * 1024),
array('1024g', 1024 * 1024 * 1024 * 1024),
array('1024G', 1024 * 1024 * 1024 * 1024)
);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function setUp() {