forked from projects/file-explorer
80 lines
2.0 KiB
PHP
80 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Service;
|
|
|
|
use App\Objects\DirContent;
|
|
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
|
use Symfony\Component\Filesystem\Exception\IOException;
|
|
use Symfony\Component\Filesystem\Filesystem;
|
|
use Symfony\Component\Finder\Finder;
|
|
use Symfony\Component\HttpFoundation\File\UploadedFile;
|
|
|
|
class FileSystemService
|
|
{
|
|
public function __construct(
|
|
#[Autowire(env: 'DATA_DIR')]
|
|
private readonly string $dir,
|
|
private readonly Filesystem $filesystem,
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* @return DirContent[]
|
|
*/
|
|
public function getDirs(string $dirs): array
|
|
{
|
|
$finder = new Finder();
|
|
$finder->in($this->getTotalPath($dirs));
|
|
|
|
$contents = [];
|
|
|
|
foreach ($finder->depth(0) as $content) {
|
|
$contents[] = DirContent::make($content);
|
|
}
|
|
|
|
return $contents;
|
|
}
|
|
|
|
/**
|
|
* @param UploadedFile[] $files
|
|
*/
|
|
public function uploadFile(array $files): void
|
|
{
|
|
foreach ($files as $file) {
|
|
$this->filesystem->dumpFile($this->getTotalPath($file->getClientOriginalName()), $file->getContent());
|
|
}
|
|
}
|
|
|
|
public function isFile(string $dirs): bool
|
|
{
|
|
try {
|
|
$this->filesystem->readFile($this->getTotalPath($dirs));
|
|
} catch (IOException) {
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
public function getFile(string $filePath): DirContent
|
|
{
|
|
$dirs = explode('/', $filePath);
|
|
$fileName = array_pop($dirs);
|
|
|
|
$finder = new Finder();
|
|
$finder->in($this->getTotalPath(implode('/', $dirs)));
|
|
|
|
foreach ($finder as $file) {
|
|
if ($file->getFilename() === $fileName) {
|
|
return DirContent::make($file, $this->filesystem->readFile($this->getTotalPath($filePath)));
|
|
}
|
|
}
|
|
|
|
throw new \RuntimeException('File not found');
|
|
}
|
|
|
|
private function getTotalPath(string $filePath): string
|
|
{
|
|
return $this->dir . '/' . $filePath;
|
|
}
|
|
} |