Skip to content

Commit 74e9e7d

Browse files
committed
MaxTotalFileSize rule
1 parent dc7c3ec commit 74e9e7d

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

resources/lang/en/messages.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,5 @@
1818
'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.',
1919
'vat-invalid' => 'The :attribute is not a valid VAT ID number.',
2020
'vat-name-unknown' => 'Unknown legal name',
21+
'total-file-sizes' => 'The sum of all file sizes should not exeed :kb Kb.',
2122
];

resources/lang/sv/messages.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,5 @@
1818
'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.',
1919
'vat-invalid' => ':Attribute är ej ett giltigt momsregistreringsnummer',
2020
'vat-name-unknown' => 'Juridiskt namn saknas',
21+
'total-file-sizes' => 'Summan av filernas storlek får inte överstiga :kb Kb.',
2122
];

src/Rules/MaxTotalFileSize.php

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php
2+
3+
namespace App\Rules;
4+
5+
namespace TantHammar\LaravelRules\Rules;
6+
7+
use Illuminate\Contracts\Validation\Rule;
8+
use Storage;
9+
10+
/**
11+
* $value must be an array with files
12+
* Default max is 5 MB (5000Kb)
13+
*/
14+
class MaxTotalFileSize implements Rule
15+
{
16+
public function __construct(
17+
public int $maxKb = 5000
18+
) {}
19+
20+
public function passes($attribute, $value): bool
21+
{
22+
if(!is_array($value)) {
23+
return false;
24+
}
25+
26+
if(blank($value)) {
27+
return true;
28+
}
29+
30+
$total_size = array_reduce($value, static function ($sum, $file) {
31+
// each item is UploadedFile Object
32+
$sum += Storage::size((Storage::path($file)));
33+
return $sum;
34+
});
35+
36+
return $total_size <= ($this->maxKb * 1024);
37+
}
38+
39+
public function message(): string
40+
{
41+
return __('laravel-rules::messages.total-file-sizes', ['kb' => $this->maxKb]);
42+
}
43+
}

0 commit comments

Comments
 (0)