mirror of
https://github.com/Part-DB/Part-DB-server.git
synced 2025-07-12 19:34:31 +02:00
Delete the file associated with an attachment after an attachment is delted or changed.
This commit is contained in:
parent
87527dfdc6
commit
6b87823d5e
5 changed files with 135 additions and 17 deletions
|
@ -34,10 +34,8 @@ namespace App\Services;
|
|||
|
||||
use App\Entity\Attachments\Attachment;
|
||||
use App\Entity\Attachments\PartAttachment;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
|
||||
use Symfony\Component\Filesystem\Filesystem;
|
||||
use Symfony\Component\HttpFoundation\File\File;
|
||||
use Symfony\Component\HttpFoundation\File\UploadedFile;
|
||||
use Symfony\Component\HttpKernel\KernelInterface;
|
||||
|
||||
|
@ -71,6 +69,21 @@ class AttachmentHelper
|
|||
return $this->base_path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an SPLFileInfo object representing the file associated with the attachment.
|
||||
* @param Attachment $attachment The attachment for which the file should be generated
|
||||
* @return \SplFileInfo|null The fileinfo for the attachment file. Null, if the attachment is external or has
|
||||
* invalid file.
|
||||
*/
|
||||
public function attachmentToFile(Attachment $attachment) : ?\SplFileInfo
|
||||
{
|
||||
if ($attachment->isExternal() || !$this->isFileExisting($attachment)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new \SplFileInfo($this->toAbsoluteFilePath($attachment));
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an relative placeholder filepath (with %MEDIA% or older %BASE%) to an absolute filepath on disk.
|
||||
* @param string $placeholder_path The filepath with placeholder for which the real path should be determined.
|
||||
|
|
|
@ -33,6 +33,7 @@ namespace App\Services;
|
|||
|
||||
use App\Entity\Attachments\Attachment;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\Filesystem\Filesystem;
|
||||
use Symfony\Component\HttpFoundation\File\File;
|
||||
|
||||
/**
|
||||
|
@ -66,4 +67,22 @@ class AttachmentReverseSearch
|
|||
return $repo->findBy(['path' => [$relative_path_new, $relative_path_old]]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the given file if it is not used by more than $threshold attachments
|
||||
* @param \SplFileInfo $file The file that should be removed
|
||||
* @param int $threshold The threshold used, to determine if a file should be deleted or not.
|
||||
* @return bool True, if the file was delete. False if not.
|
||||
*/
|
||||
public function deleteIfNotUsed(\SplFileInfo $file, int $threshold = 0) : bool
|
||||
{
|
||||
/* When the file is used more then $threshold times, don't delete it */
|
||||
if (count($this->findAttachmentsByFile($file)) > $threshold) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$fs = new Filesystem();
|
||||
$fs->remove($file);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue