Skip to content

Commit

Permalink
MaxTotalFileSize rule
Browse files Browse the repository at this point in the history
  • Loading branch information
tanthammar committed Oct 12, 2022
1 parent dc7c3ec commit 74e9e7d
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
1 change: 1 addition & 0 deletions resources/lang/en/messages.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@
'vat-service-unavailable' => 'Sorry, but the "VIES EU Vat service" is unavailable. Unable to validate your Vat ID. Please try again later or contact support for personal assistance.',
'vat-invalid' => 'The :attribute is not a valid VAT ID number.',
'vat-name-unknown' => 'Unknown legal name',
'total-file-sizes' => 'The sum of all file sizes should not exeed :kb Kb.',
];
1 change: 1 addition & 0 deletions resources/lang/sv/messages.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@
'vat-service-unavailable' => 'Tyvärr svarar inte "VIES EU Vat test service". Det är därför omöjligt att verifiera ditt Moms-nr. Vänligen försök om en stund igen eller kontakta support för manuell hantering.',
'vat-invalid' => ':Attribute är ej ett giltigt momsregistreringsnummer',
'vat-name-unknown' => 'Juridiskt namn saknas',
'total-file-sizes' => 'Summan av filernas storlek får inte överstiga :kb Kb.',
];
43 changes: 43 additions & 0 deletions src/Rules/MaxTotalFileSize.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace App\Rules;

namespace TantHammar\LaravelRules\Rules;

use Illuminate\Contracts\Validation\Rule;
use Storage;

/**
* $value must be an array with files
* Default max is 5 MB (5000Kb)
*/
class MaxTotalFileSize implements Rule
{
public function __construct(
public int $maxKb = 5000
) {}

public function passes($attribute, $value): bool
{
if(!is_array($value)) {
return false;
}

if(blank($value)) {
return true;
}

$total_size = array_reduce($value, static function ($sum, $file) {
// each item is UploadedFile Object
$sum += Storage::size((Storage::path($file)));
return $sum;
});

return $total_size <= ($this->maxKb * 1024);
}

public function message(): string
{
return __('laravel-rules::messages.total-file-sizes', ['kb' => $this->maxKb]);
}
}

0 comments on commit 74e9e7d

Please sign in to comment.