Files
kiri-core/HttpServer/Http/File.php
T

104 lines
1.9 KiB
PHP
Raw Normal View History

2020-08-31 01:27:08 +08:00
<?php
2020-10-29 18:17:25 +08:00
declare(strict_types=1);
2020-08-31 01:27:08 +08:00
namespace HttpServer\Http;
use Exception;
2020-08-31 12:38:32 +08:00
use Snowflake\Snowflake;
2020-08-31 01:27:08 +08:00
/**
* Class File
*/
class File
{
2020-10-29 18:17:25 +08:00
public string $name = '';
2021-04-15 14:43:59 +08:00
public mixed $tmp_name = '';
public mixed $error = '';
public mixed $type = '';
public mixed $size = '';
2020-08-31 01:27:08 +08:00
2021-05-13 18:44:08 +08:00
private string $_content = '';
2020-10-29 18:17:25 +08:00
private string $newName = '';
private array $errorInfo = [
2020-08-31 01:27:08 +08:00
0 => 'UPLOAD_ERR_OK.',
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.',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.'
];
/**
* @param string $path
* @return bool
* @throws Exception
*/
2020-12-25 15:57:52 +08:00
public function saveTo(string $path): bool
2020-08-31 01:27:08 +08:00
{
if ($this->hasError()) {
throw new Exception($this->getErrorInfo());
}
2021-05-13 18:52:45 +08:00
file_put_contents($path, $this->_content);
2020-08-31 01:27:08 +08:00
if (!file_exists($path)) {
return false;
}
return true;
}
/**
* @return string
2021-05-13 18:41:39 +08:00
* @throws Exception
2020-08-31 01:27:08 +08:00
*/
2020-12-25 15:57:52 +08:00
public function rename(): string
2020-08-31 01:27:08 +08:00
{
if (!empty($this->newName)) {
return $this->newName;
}
2021-05-13 18:44:08 +08:00
2021-05-13 18:52:45 +08:00
$this->_content = file_get_contents($this->getTmpPath());
$this->newName = md5($this->_content);
2021-05-13 18:45:07 +08:00
2021-05-13 18:46:22 +08:00
// $this->newName = Snowflake::rename($this->getTmpPath());
2020-08-31 01:27:08 +08:00
return $this->newName;
}
2021-04-15 15:32:34 +08:00
2020-08-31 01:27:08 +08:00
/**
* @return string
*/
2020-12-25 15:57:52 +08:00
public function getTmpPath(): string
2020-08-31 01:27:08 +08:00
{
return $this->tmp_name;
}
/**
* @return bool
*
* check file have error
*/
2020-12-25 15:57:52 +08:00
public function hasError(): bool
2020-08-31 01:27:08 +08:00
{
return $this->error !== 0;
}
/**
* @return mixed
*
* get upload error info
*/
2020-12-25 15:57:52 +08:00
public function getErrorInfo(): mixed
2020-08-31 01:27:08 +08:00
{
if (!isset($this->errorInfo[$this->error])) {
return 'Unknown upload error.';
}
return $this->errorInfo[$this->error];
}
}