|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
|
|
6
|
|
|
namespace Enjoys\Upload\Rule; |
|
7
|
|
|
|
|
8
|
|
|
|
|
9
|
|
|
use Enjoys\Upload\Exception\RuleException; |
|
10
|
|
|
use Enjoys\Upload\RuleInterface; |
|
11
|
|
|
use Psr\Http\Message\UploadedFileInterface; |
|
12
|
|
|
|
|
13
|
|
|
final class Size implements RuleInterface |
|
14
|
|
|
{ |
|
15
|
|
|
private string $errorGreaterMessage; |
|
16
|
|
|
private string $errorLessMessage; |
|
17
|
|
|
private ?int $minSize = null; |
|
18
|
|
|
private ?int $maxSize = null; |
|
19
|
|
|
|
|
20
|
8 |
|
public function __construct(string $errorGreaterMessage = null, string $errorLessMessage = null) |
|
21
|
|
|
{ |
|
22
|
8 |
|
$this->errorGreaterMessage = $errorGreaterMessage ?? 'File size is too large (%3$s, %4$s bytes). Must be less than: %1$s (%2$s bytes)'; |
|
23
|
8 |
|
$this->errorLessMessage = $errorLessMessage ?? 'File size is too small (%3$s, %4$s bytes). Must be greater than or equal to: %1$s (%2$s bytes)'; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
4 |
|
public function setMaxSize(int $maxSize): Size |
|
27
|
|
|
{ |
|
28
|
4 |
|
$this->maxSize = $maxSize; |
|
29
|
4 |
|
return $this; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
4 |
|
public function setMinSize(int $minSize): Size |
|
33
|
|
|
{ |
|
34
|
4 |
|
$this->minSize = $minSize; |
|
35
|
4 |
|
return $this; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
8 |
|
public function check(UploadedFileInterface $file): void |
|
39
|
|
|
{ |
|
40
|
8 |
|
$fileSize = $file->getSize() ?? 0; |
|
41
|
8 |
|
if ($this->maxSize !== null) { |
|
42
|
4 |
|
if ($fileSize > $this->maxSize) { |
|
43
|
2 |
|
throw new RuleException( |
|
44
|
2 |
|
sprintf( |
|
45
|
2 |
|
$this->errorGreaterMessage, |
|
46
|
2 |
|
$this->convertBytesToMegaBytes($this->maxSize), |
|
47
|
2 |
|
$this->maxSize, |
|
48
|
2 |
|
$this->convertBytesToMegaBytes($fileSize), |
|
49
|
2 |
|
$fileSize |
|
50
|
2 |
|
) |
|
51
|
2 |
|
); |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
6 |
|
if ($this->minSize !== null) { |
|
56
|
4 |
|
if ($fileSize < $this->minSize) { |
|
57
|
2 |
|
throw new RuleException( |
|
58
|
2 |
|
sprintf( |
|
59
|
2 |
|
$this->errorLessMessage, |
|
60
|
2 |
|
$this->convertBytesToMegaBytes($this->minSize), |
|
61
|
2 |
|
$this->minSize, |
|
62
|
2 |
|
$this->convertBytesToMegaBytes($fileSize), |
|
63
|
2 |
|
$fileSize |
|
64
|
2 |
|
) |
|
65
|
2 |
|
); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
4 |
|
private function convertBytesToMegaBytes(int $bytes): string |
|
71
|
|
|
{ |
|
72
|
4 |
|
return round($bytes / pow(1024, 2), 2) . ' MiB'; |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|