em = $em; $this->pathResolver = $pathResolver; } /** * Find all attachments that use the given file * @param File $file * @return Attachment[] */ public function findAttachmentsByFile(\SplFileInfo $file) : array { //Path with %MEDIA% $relative_path_new = $this->pathResolver->realPathToPlaceholder($file->getPathname()); //Path with %BASE% $relative_path_old = $this->pathResolver->realPathToPlaceholder($file->getPathname(), true); $repo = $this->em->getRepository(Attachment::class); 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; } }