Skip to content

Commit

Permalink
add default return value as parameter to use when size can not be det…
Browse files Browse the repository at this point in the history
…ermined
  • Loading branch information
ceeram committed Sep 17, 2012
1 parent 6ec0afc commit 9530e68
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
23 changes: 12 additions & 11 deletions lib/Cake/Test/Case/Utility/CakeNumberTest.php
Expand Up @@ -529,8 +529,8 @@ public function testToPercentage() {
* @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);
}

Expand All @@ -541,7 +541,7 @@ public function testFromReadableSize($size, $expected) {
* @return void
*/
public function testFromReadableSizeException() {
$result = $this->Number->fromReadableSize('bogus');
$result = $this->Number->fromReadableSize('bogus', false);
}

/**
Expand All @@ -551,14 +551,15 @@ public function testFromReadableSizeException() {
*/
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')
);
}

Expand Down
6 changes: 5 additions & 1 deletion lib/Cake/Utility/CakeNumber.php
Expand Up @@ -105,9 +105,10 @@ public static function toReadableSize($size) {
* 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;
}
Expand All @@ -120,6 +121,9 @@ public static function fromReadableSize($size) {
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.'));
}

Expand Down

0 comments on commit 9530e68

Please sign in to comment.