-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFileSizeValidator.php
More file actions
57 lines (43 loc) · 1.64 KB
/
FileSizeValidator.php
File metadata and controls
57 lines (43 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php
declare(strict_types=1);
namespace Picamator\TransferObject\Shared\Validator;
use Picamator\TransferObject\Generated\ValidatorMessageTransfer;
use Picamator\TransferObject\Shared\Environment\EnvironmentReaderInterface;
readonly class FileSizeValidator implements FileSizeValidatorInterface
{
use ValidatorMessageTrait;
private const string UNKNOWN_ERROR_MESSAGE_TEMPLATE = 'Failed to get file size for "%s".';
private const string MAX_SIZE_ERROR_MESSAGE_TEMPLATE = <<<'TEMPLATE'
File "%s" ("%d" bytes) exceeds the maximum allowed size of "%d" bytes. Please split the file into smaller parts.
TEMPLATE;
public function __construct(private EnvironmentReaderInterface $environmentReader)
{
}
public function validate(string $path): ?ValidatorMessageTransfer
{
$fileSize = $this->filesize($path);
if ($fileSize === false) {
$errorMessage = sprintf(self::UNKNOWN_ERROR_MESSAGE_TEMPLATE, $path);
return $this->createErrorMessageTransfer($errorMessage);
}
$maxFileSizeBytes = $this->getMaxFileSizeBytes();
if ($fileSize > $maxFileSizeBytes) {
$errorMessage = sprintf(
self::MAX_SIZE_ERROR_MESSAGE_TEMPLATE,
$path,
$fileSize,
$maxFileSizeBytes,
);
return $this->createErrorMessageTransfer($errorMessage);
}
return null;
}
private function getMaxFileSizeBytes(): int
{
return $this->environmentReader->getMaxFileSizeBytes();
}
protected function filesize(string $path): int|false
{
return @filesize($path);
}
}