Completed
Push — master ( 2e8a37...e129ff )
by Tobias
04:00
created

UploadedFile::setClientFilename()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2
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
    /**
20
     * @var int[]
21
     */
22
    private static $errors = [
23
        UPLOAD_ERR_OK,
24
        UPLOAD_ERR_INI_SIZE,
25
        UPLOAD_ERR_FORM_SIZE,
26
        UPLOAD_ERR_PARTIAL,
27
        UPLOAD_ERR_NO_FILE,
28
        UPLOAD_ERR_NO_TMP_DIR,
29
        UPLOAD_ERR_CANT_WRITE,
30
        UPLOAD_ERR_EXTENSION,
31
    ];
32
33
    /**
34
     * @var string
35
     */
36
    private $clientFilename;
37
38
    /**
39
     * @var string
40
     */
41
    private $clientMediaType;
42
43
    /**
44
     * @var int
45
     */
46
    private $error;
47
48
    /**
49
     * @var null|string
50
     */
51
    private $file;
52
53
    /**
54
     * @var bool
55
     */
56
    private $moved = false;
57
58
    /**
59
     * @var int
60
     */
61
    private $size;
62
63
    /**
64
     * @var StreamInterface|null
65
     */
66
    private $stream;
67
68
    /**
69
     * @param StreamInterface|string|resource $streamOrFile
70
     * @param int                             $size
71
     * @param int                             $errorStatus
72
     * @param string|null                     $clientFilename
73
     * @param string|null                     $clientMediaType
74
     */
75 70
    public function __construct(
76
        $streamOrFile,
77
        $size,
78
        $errorStatus,
79
        $clientFilename = null,
80
        $clientMediaType = null
81
    ) {
82 70
        $this->setError($errorStatus);
83 61
        $this->setSize($size);
84 57
        $this->setClientFilename($clientFilename);
85 51
        $this->setClientMediaType($clientMediaType);
86
87 45
        if ($this->isOk()) {
88 23
            $this->setStreamOrFile($streamOrFile);
89
        }
90 38
    }
91
92
    /**
93
     * Depending on the value set file or stream variable.
94
     *
95
     * @param mixed $streamOrFile
96
     *
97
     * @throws InvalidArgumentException
98
     */
99 23
    private function setStreamOrFile($streamOrFile)
100
    {
101 23
        if (is_string($streamOrFile)) {
102 2
            $this->file = $streamOrFile;
103 21
        } elseif (is_resource($streamOrFile)) {
104 2
            $this->stream = Stream::createFromResource($streamOrFile);
105 19
        } elseif ($streamOrFile instanceof StreamInterface) {
106 12
            $this->stream = $streamOrFile;
107
        } else {
108 7
            throw new InvalidArgumentException('Invalid stream or file provided for UploadedFile');
109
        }
110 16
    }
111
112
    /**
113
     * @param int $error
114
     *
115
     * @throws InvalidArgumentException
116
     */
117 70
    private function setError($error)
118
    {
119 70
        if (false === is_int($error)) {
120 7
            throw new InvalidArgumentException('Upload file error status must be an integer');
121
        }
122
123 63
        if (false === in_array($error, self::$errors)) {
124 2
            throw new InvalidArgumentException('Invalid error status for UploadedFile');
125
        }
126
127 61
        $this->error = $error;
128 61
    }
129
130
    /**
131
     * @param int $size
132
     *
133
     * @throws InvalidArgumentException
134
     */
135 61
    private function setSize($size)
136
    {
137 61
        if (false === is_int($size)) {
138 4
            throw new InvalidArgumentException('Upload file size must be an integer');
139
        }
140
141 57
        $this->size = $size;
142 57
    }
143
144
    /**
145
     * @param mixed $param
146
     *
147
     * @return bool
148
     */
149 57
    private function isStringOrNull($param)
150
    {
151 57
        return in_array(gettype($param), ['string', 'NULL']);
152
    }
153
154
    /**
155
     * @param mixed $param
156
     *
157
     * @return bool
158
     */
159 12
    private function isStringNotEmpty($param)
160
    {
161 12
        return is_string($param) && false === empty($param);
162
    }
163
164
    /**
165
     * @param string|null $clientFilename
166
     *
167
     * @throws InvalidArgumentException
168
     */
169 57
    private function setClientFilename($clientFilename)
170
    {
171 57
        if (false === $this->isStringOrNull($clientFilename)) {
172 6
            throw new InvalidArgumentException('Upload file client filename must be a string or null');
173
        }
174
175 51
        $this->clientFilename = $clientFilename;
176 51
    }
177
178
    /**
179
     * @param string|null $clientMediaType
180
     *
181
     * @throws InvalidArgumentException
182
     */
183 51
    private function setClientMediaType($clientMediaType)
184
    {
185 51
        if (false === $this->isStringOrNull($clientMediaType)) {
186 6
            throw new InvalidArgumentException('Upload file client media type must be a string or null');
187
        }
188
189 45
        $this->clientMediaType = $clientMediaType;
190 45
    }
191
192
    /**
193
     * Return true if there is no upload error.
194
     *
195
     * @return bool
196
     */
197 45
    private function isOk()
198
    {
199 45
        return $this->error === UPLOAD_ERR_OK;
200
    }
201
202
    /**
203
     * @return bool
204
     */
205 16
    public function isMoved()
206
    {
207 16
        return $this->moved;
208
    }
209
210
    /**
211
     * @throws RuntimeException if is moved or not ok
212
     */
213 30
    private function validateActive()
214
    {
215 30
        if (false === $this->isOk()) {
216 14
            throw new RuntimeException('Cannot retrieve stream due to upload error');
217
        }
218
219 16
        if ($this->isMoved()) {
220 2
            throw new RuntimeException('Cannot retrieve stream after it has already been moved');
221
        }
222 16
    }
223
224
    /**
225
     * {@inheritdoc}
226
     *
227
     * @throws RuntimeException if the upload was not successful
228
     */
229 14
    public function getStream()
230
    {
231 14
        $this->validateActive();
232
233 7
        if ($this->stream instanceof StreamInterface) {
234 6
            return $this->stream;
235
        }
236
237 1
        $resource = fopen($this->file, 'r');
238
239 1
        return Stream::createFromResource($resource);
240
    }
241
242
    /**
243
     * {@inheritdoc}
244
     *
245
     * @see http://php.net/is_uploaded_file
246
     * @see http://php.net/move_uploaded_file
247
     *
248
     * @param string $targetPath Path to which to move the uploaded file
249
     *
250
     * @throws RuntimeException         if the upload was not successful
251
     * @throws InvalidArgumentException if the $path specified is invalid
252
     * @throws RuntimeException         on any error during the move operation, or on
253
     *                                  the second or subsequent call to the method
254
     */
255 19
    public function moveTo($targetPath)
256
    {
257 19
        $this->validateActive();
258
259 12
        if (false === $this->isStringNotEmpty($targetPath)) {
260 8
            throw new InvalidArgumentException('Invalid path provided for move operation; must be a non-empty string');
261
        }
262
263 4
        if (null !== $this->file) {
264 1
            $this->moved = php_sapi_name() == 'cli'
265 1
                ? rename($this->file, $targetPath)
266 1
                : move_uploaded_file($this->file, $targetPath);
267
        } else {
268 3
            $stream = $this->getStream();
269 3
            if ($stream->isSeekable()) {
270 3
                $stream->rewind();
271
            }
272 3
            (new StreamFactory())->copyToStream(
273
                $stream,
274 3
                Stream::createFromResource(fopen($targetPath, 'w'))
275
            );
276
277 3
            $this->moved = true;
278
        }
279
280 4
        if (false === $this->moved) {
281
            throw new RuntimeException(sprintf('Uploaded file could not be moved to %s', $targetPath));
282
        }
283 4
    }
284
285
    /**
286
     * {@inheritdoc}
287
     *
288
     * @return int|null The file size in bytes or null if unknown
289
     */
290 3
    public function getSize()
291
    {
292 3
        return $this->size;
293
    }
294
295
    /**
296
     * {@inheritdoc}
297
     *
298
     * @see http://php.net/manual/en/features.file-upload.errors.php
299
     *
300
     * @return int One of PHP's UPLOAD_ERR_XXX constants
301
     */
302 10
    public function getError()
303
    {
304 10
        return $this->error;
305
    }
306
307
    /**
308
     * {@inheritdoc}
309
     *
310
     * @return string|null The filename sent by the client or null if none
311
     *                     was provided
312
     */
313 3
    public function getClientFilename()
314
    {
315 3
        return $this->clientFilename;
316
    }
317
318 3
    public function getClientMediaType()
319
    {
320 3
        return $this->clientMediaType;
321
    }
322
}
323