-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UploadedFile.php
104 lines (87 loc) · 2.39 KB
/
UploadedFile.php
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
declare(strict_types=1);
namespace SonsOfPHP\Component\HttpMessage;
use InvalidArgumentException;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UploadedFileInterface;
use RuntimeException;
/**
* {@inheritdoc}
*
* @author Joshua Estes <[email protected]>
*/
class UploadedFile implements UploadedFileInterface
{
public function __construct(
private ?StreamInterface $stream,
private readonly ?int $size = null,
private readonly int $error = \UPLOAD_ERR_OK,
private readonly ?string $clientFilename = null,
private readonly ?string $clientMediaType = null,
) {
if (!$stream instanceof StreamInterface || !$stream->isReadable()) {
throw new InvalidArgumentException('Stream is invalid');
}
if (!UploadedFileError::tryFrom($error) instanceof UploadedFileError) {
throw new InvalidArgumentException(sprintf('The value "%s" for $error is invalid.', $error));
}
}
/**
* {@inheritdoc}
*/
public function getStream(): StreamInterface
{
if (!$this->stream instanceof StreamInterface) {
throw new RuntimeException('File has already been moved');
}
return $this->stream;
}
/**
* {@inheritdoc}
*/
public function moveTo(string $targetPath): void
{
// @todo throw new \InvalidArgumentExcpetion if targetPath is invalid
if (!$this->stream instanceof StreamInterface) {
throw new RuntimeException();
}
if (false === move_uploaded_file($this->stream->getMetadata('uri'), $targetPath)) {
throw new RuntimeException('File could not be moved');
}
$this->stream = null;
}
/**
* {@inheritdoc}
*/
public function getSize(): ?int
{
if (null !== $this->size) {
return $this->size;
}
if ($this->stream instanceof StreamInterface) {
return $this->stream->getSize();
}
return null;
}
/**
* {@inheritdoc}
*/
public function getError(): int
{
return $this->error;
}
/**
* {@inheritdoc}
*/
public function getClientFilename(): ?string
{
return $this->clientFilename;
}
/**
* {@inheritdoc}
*/
public function getClientMediaType(): ?string
{
return $this->clientMediaType;
}
}