Automation/app/Libraries/MyStorage/FileLibrary.php
2024-09-09 16:40:16 +09:00

73 lines
2.3 KiB
PHP

<?php
namespace App\Libraries\MyStorage;
use App\Entities\MyStorage\FileEntity;
class FileLibrary extends MyStorageLibrary
{
private $_path = "";
public function __construct(string $path)
{
parent::__construct();
$this->_path = $path;
}
final public function getPath(): string
{
return $this->_path;
}
protected function getMediaTag(string $mediaType, FileEntity $entity): string
{
$mediaTag = "";
switch ($mediaType) {
case "image":
$mediaTag = sprintf(
"<img src=\"/%s/%s/%s\" alt=\"%s\">",
$this->getUploadPath(),
$entity->getPath(),
$entity->getTitle(),
$entity->getTitle()
);
break;
case "video":
$mediaTag = sprintf(
"<video alt=\"%s\" controls autoplay>
<source src=\"/%s/%s/%s\" type=\"%s\">
Your browser does not support the video tag.
</video>",
$entity->getTitle(),
$this->getUploadPath(),
$entity->getPath(),
$entity->getTitle(),
$entity->getMimeType(),
);
break;
}
return $mediaTag;
}
public function save(string $fileName, string $mediaType, string $content, int $file_sequence): null|FileEntity
{
$fullPath = WRITEPATH . $this->getUploadPath() . DIRECTORY_SEPARATOR . $this->getPath();
if (!is_dir($fullPath)) {
if (!mkdir($fullPath)) {
throw new \Exception("Make Directory Error:" . $fullPath);
}
}
$saveFilePath = $fullPath . DIRECTORY_SEPARATOR . $fileName;
log_message("debug", "Storage Save-> " . $saveFilePath);
if (!file_put_contents($saveFilePath, $content)) {
return null;
}
$entity = new FileEntity();
$entity->setPath($this->getPath());
$entity->setTitle($fileName);
$entity->setMimeType(mime_content_type($saveFilePath));
$entity->setSize(filesize($saveFilePath));
$entity->setMediaHTML($this->getMediaTag($mediaType, $entity));
return $entity;
}
}