Skip to content

Commit

Permalink
Add File::sizeToBytes() helper
Browse files Browse the repository at this point in the history
  • Loading branch information
LukeTowers authored Nov 5, 2024
1 parent 752c162 commit c084923
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/Filesystem/Filesystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,45 @@ public function sizeToString(int $bytes): string
return '0 bytes';
}

/**
* Converts a file size string (e.g., "1 GB", "500 MB", "512K", "2M") to bytes.
* Returns the result as a string to handle large sizes safely.
* @throws InvalidArgumentException if it is unable to parse the provided string
*/
public function sizeToBytes(string $size): string

Check failure on line 93 in src/Filesystem/Filesystem.php

View workflow job for this annotation

GitHub Actions / Code Analysis

PHPDoc tag @throws with type Winter\Storm\Filesystem\InvalidArgumentException is not subtype of Throwable
{
// Trim whitespace and convert to lowercase for consistency
$size = strtolower(trim($size));

// Regular expression to match both human-readable (e.g., "1 GB") and PHP shorthand (e.g., "1G")
if (preg_match('/^(\d+(?:\.\d+)?)\s*(gb|g|mb|m|kb|k|bytes|byte)?$/', $size, $matches)) {
$value = (float) $matches[1]; // Numeric part of the size
$unit = $matches[2] ?? 'bytes'; // Default to bytes if no unit is provided

switch ($unit) {
case 'gb':
case 'g':
$value = ($value * 1024 * 1024 * 1024);
case 'mb':
case 'm':
$value = ($value * 1024 * 1024);
case 'kb':
case 'k':
$value = ($value * 1024);
case 'byte':
case 'bytes':
$value = $value;
default:
throw new \InvalidArgumentException("Unknown size unit '$unit'");
}

return (string) $value;

Check failure on line 120 in src/Filesystem/Filesystem.php

View workflow job for this annotation

GitHub Actions / Code Analysis

Unreachable statement - code above always terminates.
}

throw new \InvalidArgumentException("Invalid size format '$size'");
}


/**
* Returns a public file path from an absolute path.
*
Expand Down

0 comments on commit c084923

Please sign in to comment.