cfmgrv4/app/Traits/FileTrait.php
2025-02-11 10:00:38 +09:00

63 lines
2.0 KiB
PHP

<?php
namespace App\Traits;
trait FileTrait
{
final protected function mkdir_FileTrait(string $path)
{
if (!is_dir($path)) {
if (!mkdir($path, 0755, true)) {
throw new \Exception("디렉토리 생성 실패:{$path}");
}
}
}
final protected function isFileType_FileTrait(string $file_ext, string $type = "img"): bool
{
switch ($type) {
case "audio":
$exts = ['wav', 'mp3'];
break;
case "video":
$exts = ['mov', 'avi', 'mp4'];
break;
case "img":
default:
$exts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
break;
}
return in_array($file_ext, $exts);
}
// 디렉토리에 속한 파일 List
final protected function getFiles_FileTrait(string $path, string $type = "img"): array
{
// 디렉토리에서 파일 목록 가져오기
$files = [];
foreach (scandir($path) as $file_name) {
// 확장자가 이미지 형식인지 확인
$file_ext = pathinfo($path . DIRECTORY_SEPARATOR . $file_name, PATHINFO_EXTENSION);
if ($this->isFileType_FileTrait($file_ext, $type)) {
$files[] = $file_name;
}
}
return $files;
}
final protected function getUniqueName_FileTrait(string $path, string $file_name): string
{
$fileExtension = pathinfo($file_name, PATHINFO_EXTENSION);
$fileBaseName = pathinfo($file_name, PATHINFO_FILENAME);
$newFilename = $file_name;
$counter = 1;
// 중복된 파일명이 존재하는지 확인
while (file_exists($path . DIRECTORY_SEPARATOR . $newFilename)) {
// 중복된 파일명이 존재하면 숫자를 추가하여 새로운 파일명 생성
$newFilename = $fileBaseName . '_' . $counter . '.' . $fileExtension;
$counter++;
}
return $newFilename;
}
}