49 lines
1.5 KiB
PHP
49 lines
1.5 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Esun\FileManager\Model;
|
|
|
|
use Magento\Framework\App\Filesystem\DirectoryList;
|
|
use Magento\Framework\Exception\LocalizedException;
|
|
use Magento\Framework\Filesystem;
|
|
use Magento\Framework\Filesystem\Directory\WriteInterface;
|
|
use Esun\FileManager\Model\ResourceModel\File as FileResource;
|
|
|
|
class DeleteService
|
|
{
|
|
private WriteInterface $mediaDirectory;
|
|
|
|
public function __construct(
|
|
Filesystem $filesystem,
|
|
private readonly FileResource $fileResource
|
|
) {
|
|
$this->mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
|
|
}
|
|
|
|
/**
|
|
* @throws LocalizedException
|
|
*/
|
|
public function delete(File $file): void
|
|
{
|
|
$relativePath = str_replace('\\', '/', (string) $file->getData('filepath'));
|
|
if (!preg_match('#^uploads(?:/[\p{L}\p{N}._-]+)+$#u', $relativePath)
|
|
|| str_contains($relativePath, '..')
|
|
) {
|
|
throw new LocalizedException(__('The stored file path is invalid.'));
|
|
}
|
|
|
|
$connection = $this->fileResource->getConnection();
|
|
$connection->beginTransaction();
|
|
try {
|
|
$this->fileResource->delete($file);
|
|
if ($this->mediaDirectory->isFile($relativePath)) {
|
|
$this->mediaDirectory->delete($relativePath);
|
|
}
|
|
$connection->commit();
|
|
} catch (\Throwable $exception) {
|
|
$connection->rollBack();
|
|
throw new LocalizedException(__('The file could not be deleted.'), $exception);
|
|
}
|
|
}
|
|
}
|