add default return value as parameter to use when size can not be determined

This commit is contained in:
Ceeram 2012-09-17 11:29:13 +02:00
parent 6ec0afcf5d
commit 9530e68ae6
2 changed files with 17 additions and 12 deletions

View file

@ -529,8 +529,8 @@ class CakeNumberTest extends CakeTestCase {
* @dataProvider filesizes
* @return void
*/
public function testFromReadableSize($size, $expected) {
$result = $this->Number->fromReadableSize($size);
public function testFromReadableSize($params, $expected) {
$result = $this->Number->fromReadableSize($params['size'], $params['default']);
$this->assertEquals($expected, $result);
}
@ -541,7 +541,7 @@ class CakeNumberTest extends CakeTestCase {
* @return void
*/
public function testFromReadableSizeException() {
$result = $this->Number->fromReadableSize('bogus');
$result = $this->Number->fromReadableSize('bogus', false);
}
/**
@ -551,14 +551,15 @@ class CakeNumberTest extends CakeTestCase {
*/
public function filesizes() {
return array(
array('512B', 512),
array('1KB', 1024),
array('1.5KB', 1536),
array('1MB', 1048576),
array('1.5MB', 1572864),
array('1GB', 1073741824),
array('1.5GB', 1610612736),
array('512', 512),
array(array('size' => '512B', 'default' => false), 512),
array(array('size' => '1KB', 'default' => false), 1024),
array(array('size' => '1.5KB', 'default' => false), 1536),
array(array('size' => '1MB', 'default' => false), 1048576),
array(array('size' => '1.5MB', 'default' => false), 1572864),
array(array('size' => '1GB', 'default' => false), 1073741824),
array(array('size' => '1.5GB', 'default' => false), 1610612736),
array(array('size' => '512', 'default' => 'Unknown type'), 512),
array(array('size' => '2VB', 'default' => 'Unknown type'), 'Unknown type')
);
}

View file

@ -105,9 +105,10 @@ class CakeNumber {
* Converts filesize from human readable string to bytes
*
* @param string $size Size in human readable string like '5MB'
* @param mixed $default Value to be returned when invalid size was used, for example 'Unknown type'
* @return integer Bytes
*/
public static function fromReadableSize($size) {
public static function fromReadableSize($size, $default = false) {
if (ctype_digit($size)) {
return $size * 1;
}
@ -120,6 +121,9 @@ class CakeNumber {
if (substr($size, -1) == 'B' && ctype_digit(substr($size, 0, strlen($size) - 1))) {
return $size * 1;
}
if ($default !== false) {
return $default;
}
throw new CakeException(__d('cake_dev', 'No unit type.'));
}