Completed
Push — master ( 4e07a2...96fcad )
by Tobias
03:18
created

UploadedFile::setSize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 5
cp 0.8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2.032
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Nyholm\Psr7;
6
7
use InvalidArgumentException;
8
use Nyholm\Psr7\Factory\StreamFactory;
9
use Psr\Http\Message\StreamInterface;
10
use Psr\Http\Message\UploadedFileInterface;
11
use RuntimeException;
12
13
/**
14
 * @author Michael Dowling and contributors to guzzlehttp/psr7
15
 * @author Tobias Nyholm <[email protected]>
16
 */
17
class UploadedFile implements UploadedFileInterface
18
{
19
    /** @var int[] */
20
    private static $errors = [
21
        UPLOAD_ERR_OK, UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE, UPLOAD_ERR_PARTIAL, UPLOAD_ERR_NO_FILE,
22
        UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE, UPLOAD_ERR_EXTENSION,
23
    ];
24
25
    /** @var string */
26
    private $clientFilename;
27
28
    /** @var string */
29
    private $clientMediaType;
30
31
    /** @var int */
32
    private $error;
33
34
    /** @var null|string */
35
    private $file;
36
37
    /** @var bool */
38
    private $moved = false;
39
40
    /** @var null|int */
41
    private $size;
42
43
    /** @var null|StreamInterface */
44
    private $stream;
45
46
    /**
47
     * @param StreamInterface|string|resource $streamOrFile
48
     * @param int                             $size
49
     * @param int                             $errorStatus
50
     * @param string|null                     $clientFilename
51
     * @param string|null                     $clientMediaType
52
     */
53 75
    public function __construct(
54
        $streamOrFile,
55
        $size,
56
        $errorStatus,
57
        $clientFilename = null,
58
        $clientMediaType = null
59
    ) {
60 75
        $this->setError($errorStatus);
61 66
        $this->setSize($size);
62 66
        $this->setClientFilename($clientFilename);
63 60
        $this->setClientMediaType($clientMediaType);
64
65 54
        if ($this->isOk()) {
66 32
            $this->setStreamOrFile($streamOrFile);
67
        }
68 47
    }
69
70
    /**
71
     * Depending on the value set file or stream variable.
72
     *
73
     * @param mixed $streamOrFile
74
     *
75
     * @throws InvalidArgumentException
76
     */
77 32
    private function setStreamOrFile($streamOrFile): void
78
    {
79 32
        if (is_string($streamOrFile)) {
80 1
            $this->file = $streamOrFile;
81 31
        } elseif (is_resource($streamOrFile)) {
82 1
            $this->stream = Stream::createFromResource($streamOrFile);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Nyholm\Psr7\Stream::cre...Resource($streamOrFile) of type object<self> is incompatible with the declared type null|object<Psr\Http\Message\StreamInterface> of property $stream.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
83 30
        } elseif ($streamOrFile instanceof StreamInterface) {
84 23
            $this->stream = $streamOrFile;
85
        } else {
86 7
            throw new InvalidArgumentException('Invalid stream or file provided for UploadedFile');
87
        }
88 25
    }
89
90
    /**
91
     * @param int $error
92
     *
93
     * @throws InvalidArgumentException
94
     */
95 75
    private function setError($error): void
96
    {
97 75
        if (false === is_int($error)) {
98 7
            throw new InvalidArgumentException('Upload file error status must be an integer');
99
        }
100
101 68
        if (false === in_array($error, self::$errors)) {
102 2
            throw new InvalidArgumentException('Invalid error status for UploadedFile');
103
        }
104
105 66
        $this->error = $error;
106 66
    }
107
108
    /**
109
     * @param int $size
110
     *
111
     * @throws InvalidArgumentException
112
     */
113 66
    private function setSize($size): void
114
    {
115 66
        if (false === is_int($size)) {
116
            throw new InvalidArgumentException('Upload file size must be an integer');
117
        }
118
119 66
        $this->size = $size;
120 66
    }
121
122 66
    private function isStringOrNull($param): bool
123
    {
124 66
        return in_array(gettype($param), ['string', 'NULL']);
125
    }
126
127 16
    private function isStringNotEmpty($param): bool
128
    {
129 16
        return is_string($param) && false === empty($param);
130
    }
131
132 66
    private function setClientFilename($clientFilename): void
133
    {
134 66
        if (false === $this->isStringOrNull($clientFilename)) {
135 6
            throw new InvalidArgumentException('Upload file client filename must be a string or null');
136
        }
137
138 60
        $this->clientFilename = $clientFilename;
139 60
    }
140
141 60
    private function setClientMediaType($clientMediaType): void
142
    {
143 60
        if (false === $this->isStringOrNull($clientMediaType)) {
144 6
            throw new InvalidArgumentException('Upload file client media type must be a string or null');
145
        }
146
147 54
        $this->clientMediaType = $clientMediaType;
148 54
    }
149
150
    /**
151
     * @return bool Return true if there is no upload error.
152
     */
153 54
    private function isOk(): bool
154
    {
155 54
        return UPLOAD_ERR_OK === $this->error;
156
    }
157
158
    /**
159
     * @throws RuntimeException if is moved or not ok
160
     */
161 34
    private function validateActive(): void
162
    {
163 34
        if (false === $this->isOk()) {
164 14
            throw new RuntimeException('Cannot retrieve stream due to upload error');
165
        }
166
167 20
        if ($this->moved) {
168 4
            throw new RuntimeException('Cannot retrieve stream after it has already been moved');
169
        }
170 20
    }
171
172 18
    public function getStream(): StreamInterface
173
    {
174 18
        $this->validateActive();
175
176 11
        if ($this->stream instanceof StreamInterface) {
177 11
            return $this->stream;
178
        }
179
180
        $resource = fopen($this->file, 'r');
181
182
        return Stream::createFromResource($resource);
183
    }
184
185 23
    public function moveTo($targetPath): void
186
    {
187 23
        $this->validateActive();
188
189 16
        if (false === $this->isStringNotEmpty($targetPath)) {
190 8
            throw new InvalidArgumentException('Invalid path provided for move operation; must be a non-empty string');
191
        }
192
193 8
        if (null !== $this->file) {
194 1
            $this->moved = 'cli' === php_sapi_name()
195 1
                ? rename($this->file, $targetPath)
196 1
                : move_uploaded_file($this->file, $targetPath);
197
        } else {
198 7
            $stream = $this->getStream();
199 7
            if ($stream->isSeekable()) {
200 7
                $stream->rewind();
201
            }
202 7
            (new StreamFactory())->copyToStream(
203 7
                $stream,
204 7
                Stream::createFromResource(fopen($targetPath, 'w'))
205
            );
206
207 7
            $this->moved = true;
208
        }
209
210 8
        if (false === $this->moved) {
211
            throw new RuntimeException(sprintf('Uploaded file could not be moved to %s', $targetPath));
212
        }
213 8
    }
214
215 3
    public function getSize(): ?int
216
    {
217 3
        return $this->size;
218
    }
219
220 10
    public function getError(): int
221
    {
222 10
        return $this->error;
223
    }
224
225 3
    public function getClientFilename(): ?string
226
    {
227 3
        return $this->clientFilename;
228
    }
229
230 3
    public function getClientMediaType(): ?string
231
    {
232 3
        return $this->clientMediaType;
233
    }
234
}
235