Files
kiri-core/http-message/Uploaded.php
T

119 lines
2.0 KiB
PHP
Raw Normal View History

2021-09-10 03:33:45 +08:00
<?php
2021-09-16 14:53:36 +08:00
namespace Http\Message;
2021-09-10 03:33:45 +08:00
2021-09-16 14:53:36 +08:00
use Exception;
2021-09-10 03:33:45 +08:00
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UploadedFileInterface;
class Uploaded implements UploadedFileInterface
{
2021-09-10 10:24:11 +08:00
const ERROR = [
0 => "There is no error, the file uploaded with success",
1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3 => "The uploaded file was only partially uploaded",
4 => "No file was uploaded",
6 => "Missing a temporary folder"
];
2021-09-16 14:53:36 +08:00
/**
* @var resource
*/
private mixed $stream;
2021-09-10 10:24:11 +08:00
/**
* @param string $tmp_name
* @param string $name
* @param string $type
* @param int $size
* @param int $error
*/
public function __construct(
public string $tmp_name,
public string $name,
public string $type,
public int $size,
public int $error
)
{
}
/**
* @return StreamInterface
2021-09-16 14:53:36 +08:00
* @throws Exception
2021-09-10 10:24:11 +08:00
*/
public function getStream(): StreamInterface
{
2021-09-16 14:53:36 +08:00
if ($this->stream instanceof Stream) {
return $this->stream;
2021-09-10 10:24:11 +08:00
}
2021-09-16 14:53:36 +08:00
$this->stream = new Stream(fopen($this->tmp_name, 'r+'));
return $this->stream;
2021-09-10 10:24:11 +08:00
}
/**
* @param string $targetPath
2021-09-16 14:53:36 +08:00
* @return StreamInterface
* @throws Exception
2021-09-10 10:24:11 +08:00
*/
public function moveTo($targetPath): StreamInterface
{
@move_uploaded_file($this->tmp_name, $targetPath);
if (!file_exists($targetPath)) {
2021-09-16 14:53:36 +08:00
throw new Exception('File save fail.');
2021-09-10 10:24:11 +08:00
}
2021-09-16 14:53:36 +08:00
if ($this->stream instanceof Stream) {
$this->stream->close();
$this->stream = null;
}
2021-09-10 10:24:11 +08:00
$this->tmp_name = $targetPath;
return $this->getStream();
}
/**
* @return int
*/
public function getSize(): int
{
return $this->size;
}
/**
* @return int
*/
public function getError(): int
{
return $this->error;
}
/**
* @return string
*/
public function getClientFilename(): string
{
return $this->name;
}
/**
* @return string
*/
public function getClientMediaType(): string
{
return $this->type;
}
2021-09-10 03:33:45 +08:00
}