4 use InvalidArgumentException;
14 private static $errors = [
20 UPLOAD_ERR_NO_TMP_DIR,
21 UPLOAD_ERR_CANT_WRITE,
28 private $clientFilename;
33 private $clientMediaType;
48 private $moved =
false;
71 $clientFilename =
null,
72 $clientMediaType =
null
74 $this->setError($errorStatus);
75 $this->setSize($size);
76 $this->setClientFilename($clientFilename);
77 $this->setClientMediaType($clientMediaType);
80 $this->setStreamOrFile($streamOrFile);
90 private function setStreamOrFile($streamOrFile)
92 if (is_string($streamOrFile)) {
93 $this->file = $streamOrFile;
94 } elseif (is_resource($streamOrFile)) {
95 $this->stream =
new Stream($streamOrFile);
97 $this->stream = $streamOrFile;
100 'Invalid stream or file provided for UploadedFile'
109 private function setError($error)
111 if (
false === is_int($error)) {
113 'Upload file error status must be an integer'
117 if (
false === in_array($error, UploadedFile::$errors)) {
119 'Invalid error status for UploadedFile'
123 $this->error = $error;
130 private function setSize($size)
132 if (
false === is_int($size)) {
134 'Upload file size must be an integer'
145 private function isStringOrNull($param)
147 return in_array(gettype($param), [
'string',
'NULL']);
154 private function isStringNotEmpty($param)
156 return is_string($param) &&
false === empty($param);
163 private function setClientFilename($clientFilename)
165 if (
false === $this->isStringOrNull($clientFilename)) {
167 'Upload file client filename must be a string or null'
171 $this->clientFilename = $clientFilename;
178 private function setClientMediaType($clientMediaType)
180 if (
false === $this->isStringOrNull($clientMediaType)) {
182 'Upload file client media type must be a string or null'
186 $this->clientMediaType = $clientMediaType;
194 private function isOk()
196 return $this->error === UPLOAD_ERR_OK;
210 private function validateActive()
212 if (
false === $this->isOk()) {
213 throw new RuntimeException(
'Cannot retrieve stream due to upload error');
217 throw new RuntimeException(
'Cannot retrieve stream after it has already been moved');
227 $this->validateActive();
230 return $this->stream;
247 public function moveTo($targetPath)
249 $this->validateActive();
251 if (
false === $this->isStringNotEmpty($targetPath)) {
253 'Invalid path provided for move operation; must be a non-empty string'
258 $this->moved = php_sapi_name() ==
'cli'
259 ? rename($this->file, $targetPath)
260 : move_uploaded_file($this->file, $targetPath);
270 if (
false === $this->moved) {
271 throw new RuntimeException(
272 sprintf(
'Uploaded file could not be moved to %s', $targetPath)
306 return $this->clientFilename;
314 return $this->clientMediaType;