Last active
September 7, 2024 02:10
-
-
Save cursosdesarrolloweb/79e674cdbfd8110c3e3c2205d2246ed5 to your computer and use it in GitHub Desktop.
Get the max upload size from desired and php.ini config with Laravel
This file contains hidden or 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
<?php | |
namespace App\Services; | |
use Exception; | |
use Illuminate\Http\UploadedFile; | |
final class MaxUploadSizeService | |
{ | |
const BYTES = 'B'; | |
const KILOBYTES = 'KB'; | |
const MEGABYTES = 'MB'; | |
const GIGABYTES = 'GB'; | |
private static array $sizeTypes = [ | |
self::BYTES, | |
self::KILOBYTES, | |
self::MEGABYTES, | |
self::GIGABYTES, | |
]; | |
/** | |
* @throws Exception | |
*/ | |
public static function getMaxUploadSize(string $desired = '2M', string $sizeType = 'MB'): int|float | |
{ | |
if (! in_array($sizeType, self::$sizeTypes)) | |
{ | |
throw new Exception('Size type not found!'); | |
} | |
$desiredMaxSize = ini_parse_quantity($desired); | |
$phpIniMaxSize = UploadedFile::getMaxFilesize(); | |
$maxSize = min($desiredMaxSize, $phpIniMaxSize); | |
return self::convert($maxSize, $sizeType); | |
} | |
private static function convert(int $bytes, string $sizeType): int|float | |
{ | |
$divisor = pow(1024, array_search($sizeType, self::$sizeTypes)); | |
return $bytes / $divisor; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment