-
-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
752c162
commit c084923
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 GitHub Actions / Code Analysis
|
||
{ | ||
// 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; | ||
} | ||
|
||
throw new \InvalidArgumentException("Invalid size format '$size'"); | ||
} | ||
|
||
|
||
/** | ||
* Returns a public file path from an absolute path. | ||
* | ||
|