Skip to content

Commit

Permalink
Added StorageHelper & SizeUnitEnum
Browse files Browse the repository at this point in the history
  • Loading branch information
jzaplet committed Oct 27, 2024
1 parent 2658d81 commit ee50fb3
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 0 deletions.
65 changes: 65 additions & 0 deletions src/Storage/SizeUnit.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);

namespace Megio\Storage;

enum SizeUnit: string
{
case Bytes = 'B';
case KiloBytes = 'KB';
case MegaBytes = 'MB';
case GigaBytes = 'GB';
case TeraBytes = 'TB';
case PetaBytes = 'PB';

public static function fromPhpIniAlias(string $unit): self
{
$unit = strtoupper($unit);

return match ($unit) {
'B' => self::Bytes,
'K' => self::KiloBytes,
'M' => self::MegaBytes,
'G' => self::GigaBytes,
'T' => self::TeraBytes,
'P' => self::PetaBytes,
default => throw new \InvalidArgumentException("Invalid unit: $unit"),
};
}

public static function getIdealUnit(float $size): self
{
$unit = self::Bytes;

while ($size >= 1024 && $unit !== self::PetaBytes) {
$size /= 1024;
$unit = match ($unit) {
self::Bytes => self::KiloBytes,
self::KiloBytes => self::MegaBytes,
self::MegaBytes => self::GigaBytes,
self::GigaBytes => self::TeraBytes,
};
}

return $unit;
}

public static function convert(float $size, SizeUnit $sourceUnit, SizeUnit $targetUnit): float
{
return $size * $sourceUnit->getMultiplier($targetUnit);
}

public function getMultiplier(SizeUnit $targetUnit): float
{
$units = [
self::Bytes->value => 1,
self::KiloBytes->value => 1024,
self::MegaBytes->value => 1024 ** 2,
self::GigaBytes->value => 1024 ** 3,
self::TeraBytes->value => 1024 ** 4,
self::PetaBytes->value => 1024 ** 5,
];

return $units[$this->value] / $units[$targetUnit->value];
}
}
23 changes: 23 additions & 0 deletions src/Storage/StorageHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);

namespace Megio\Storage;

use Symfony\Component\HttpFoundation\File\UploadedFile;

class StorageHelper
{
public static function getMaxFileSize(SizeUnit $targetUnit = SizeUnit::Bytes): float
{
$iniMaxFileSize = (string)ini_get('upload_max_filesize');
$iniUnit = strtoupper(substr($iniMaxFileSize, -1));
$iniSize = (int)substr($iniMaxFileSize, 0, -1);

return SizeUnit::fromPhpIniAlias($iniUnit)->getMultiplier($targetUnit) * $iniSize;
}

public static function isFileSizeOk(UploadedFile $file): bool
{
return $file->getSize() <= self::getMaxFileSize();
}
}

0 comments on commit ee50fb3

Please sign in to comment.