Automation/app/Libraries/MyStorage/FileLibrary.php
2024-09-08 18:45:08 +09:00

81 lines
2.5 KiB
PHP

<?php
namespace App\Libraries\MyStorage;
use App\Entities\MyStorage\FileEntity;
class FileLibrary extends MyStorageLibrary
{
private $_path = "";
protected $_entity = null;
public function __construct(string $path)
{
parent::__construct();
$this->_path = $path;
}
final public function getPath(): string
{
return $this->_path;
}
public function getEntity(): FileEntity
{
if ($this->_entity === null) {
$this->_entity = new FileEntity();
$this->_entity->setPath($this->getPath());
}
return $this->_entity;
}
private function getMediaTag(string $mediaType): string
{
$mediaTag = "";
switch ($mediaType) {
case "image":
$mediaTag = sprintf(
"<img src=\"/%s/%s/%s\" alt=\"%s\">",
$this->getUploadPath(),
$this->getEntity()->getPath(),
$this->getEntity()->getTitle(),
$this->getEntity()->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>",
$this->getEntity()->getTitle(),
$this->getUploadPath(),
$this->getEntity()->getPath(),
$this->getEntity()->getTitle(),
$this->getEntity()->getMimeType(),
);
break;
}
return $mediaTag;
}
public function save(string $fileName, string $mediaType, string $content, int $file_sequence)
{
$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 false;
}
$entity = $this->getEntity();
$entity->setTitle($fileName);
$entity->setMimeType(mime_content_type($saveFilePath));
$entity->setMediaHTML($this->getMediaTag($mediaType));
return $entity;
}
}