Completed
Push — master ( a6d143...772697 )
by Tobias
06:55 queued 27s
created

src/UploadedFile.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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