| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402 |
- <?php
- declare(strict_types=1);
- namespace App\Service\File\Storage;
- use App\Entity\Access\Access;
- use App\Entity\Core\File;
- use App\Entity\Organization\Organization;
- use App\Entity\Person\Person;
- use App\Enum\Core\FileFolderEnum;
- use App\Enum\Core\FileHostEnum;
- use App\Enum\Core\FileSizeEnum;
- use App\Enum\Core\FileStatusEnum;
- use App\Enum\Core\FileTypeEnum;
- use App\Enum\Core\FileVisibilityEnum;
- use App\Repository\Access\AccessRepository;
- use App\Service\File\Factory\ImageFactory;
- use App\Service\Utils\FileUtils;
- use App\Service\Utils\PathUtils;
- use App\Service\Utils\UrlBuilder;
- use App\Service\Utils\Uuid;
- use Doctrine\ORM\EntityManagerInterface;
- use Gaufrette\FilesystemInterface;
- use JetBrains\PhpStorm\Pure;
- use Knp\Bundle\GaufretteBundle\FilesystemMap;
- use Liip\ImagineBundle\Imagine\Cache\CacheManager;
- use Liip\ImagineBundle\Imagine\Data\DataManager;
- /**
- * Read and write files into the file storage.
- */
- class LocalStorage implements FileStorageInterface
- {
- /**
- * Key of the gaufrette storage, as defined in config/packages/knp_gaufrette.yaml.
- */
- protected const FS_KEY = 'storage';
- // Cache Image Folder
- protected const SM_FOLDER = 'sm';
- protected const MD_FOLDER = 'md';
- protected const LG_FOLDER = 'lg';
- protected const CROP_SM = 'crop_sm';
- protected const CROP_MD = 'crop_md';
- protected const CROP_LG = 'crop_lg';
- protected FilesystemInterface $filesystem;
- public function __construct(
- protected readonly FilesystemMap $filesystemMap,
- protected readonly EntityManagerInterface $entityManager,
- protected readonly AccessRepository $accessRepository,
- protected readonly DataManager $dataManager,
- protected readonly CacheManager $cacheManager,
- protected readonly ImageFactory $imageFactory,
- protected readonly FileUtils $fileUtils,
- protected readonly UrlBuilder $urlBuilder,
- protected readonly string $fileStorageDir,
- ) {
- $this->filesystem = $filesystemMap->get(static::FS_KEY);
- }
- /**
- * Return true if the file exists in the file storage.
- */
- public function exists(File $file): bool
- {
- return $this->filesystem->has($file->getSlug());
- }
- /**
- * Lists all the non-temporary files of the given owner.
- *
- * @return list<string>
- */
- public function listByOwner(
- Organization|Access|Person $owner,
- ?FileTypeEnum $type = null,
- ): array {
- return $this->filesystem->listKeys(
- $this->getPrefix($owner, false, $type)
- );
- }
- /**
- * Reads the given file and returns its content as a string.
- */
- public function read(File $file): string
- {
- return $this->filesystem->read($file->getSlug());
- }
- /**
- * Retourne l'URL de l'image, à la bonne taille, contenu dans le File.
- */
- public function getImageUrl(File $file, string $size, bool $relativePath, bool $uncropped = false): string
- {
- $crop = !empty($file->getConfig()) && !$uncropped;
- $filterName = $this->getFilterFromSizeAndConfig($size, $crop);
- $path = $file->getSlug();
- if (!$this->cacheManager->isStored($path, $filterName)) {
- try {
- $this->imageFactory->createImageContent($file, $filterName, $uncropped);
- } catch (\Exception $e) {
- $path = 'images/missing-file.png';
- return $relativePath ? $path : $this->urlBuilder->getAbsoluteUrl($path);
- }
- }
- $url = $this->cacheManager->resolve($path, $filterName);
- return $relativePath ? $this->urlBuilder->getRelativeUrl($url) : $url;
- }
- /**
- * Retourne le filtre Liip correspondant à la taille désirée.
- */
- protected function getFilterFromSizeAndConfig(string $size, bool $crop = true): string
- {
- switch ($size) {
- case FileSizeEnum::SM->value :
- $filter = $crop ? self::CROP_SM : self::SM_FOLDER;
- break;
- case FileSizeEnum::MD->value :
- default:
- $filter = $crop ? self::CROP_MD : self::MD_FOLDER;
- break;
- case FileSizeEnum::LG->value :
- $filter = $crop ? self::CROP_LG : self::LG_FOLDER;
- break;
- }
- return $filter;
- }
- /**
- * Prepare a File record with a PENDING status.
- * This record will hold all the data needed to create the file, except its content.
- *
- * @param Organization|Access|Person $owner Owner of the file, either an organization, a person or both (access)
- * @param string $filename The file's name (mandatory)
- * @param FileTypeEnum $type The type of the new file
- * @param Access $createdBy Id of the access responsible for this creation
- * @param bool $isTemporary Is it a temporary file that can be deleted after some time
- * @param string|null $mimeType Mimetype of the file, if not provided, the method will try to guess it from its file name's extension
- * @param bool $flushFile Should the newly created file be flushed after having been persisted?
- * @param FileFolderEnum|null $folder The folder where the file is stored, designed for document management
- */
- public function prepareFile(
- Organization|Access|Person $owner,
- string $filename,
- FileTypeEnum $type,
- Access $createdBy,
- bool $isTemporary = false,
- FileVisibilityEnum $visibility = FileVisibilityEnum::NOBODY,
- ?string $mimeType = null,
- bool $flushFile = true,
- ?FileFolderEnum $folder = FileFolderEnum::UNRATED,
- ): File {
- [$organization, $person] = $this->getOrganizationAndPersonFromOwner($owner);
- $file = (new File())
- ->setName($filename)
- ->setSlug(null)
- ->setOrganization($organization)
- ->setPerson($person)
- ->setType($type)
- ->setVisibility($visibility)
- ->setIsTemporaryFile($isTemporary)
- ->setMimeType($mimeType ?? $this->fileUtils->guessMimeTypeFromFilename($filename))
- ->setCreateDate(new \DateTime())
- ->setCreatedBy($createdBy->getId())
- ->setFolder($folder)
- ->setStatus(FileStatusEnum::PENDING);
- $this->entityManager->persist($file);
- if ($flushFile) {
- $this->entityManager->flush();
- }
- return $file;
- }
- /**
- * Write the $content into the file storage and update the given File object's size, slug, status (READY)...
- *
- * @param File $file The file object that is about to be written
- * @param string $content The content of the file
- * @param Access $author The access responsible for the creation / update of the file
- */
- public function write(File $file, string $content, Access $author): File
- {
- if (empty($file->getName())) {
- throw new \RuntimeException('File has no filename');
- }
- try {
- $isNewFile = $file->getSlug() === null;
- } catch (\Throwable) {
- $isNewFile = true; // Catch case where slud has not been initialized
- }
- if ($isNewFile) {
- // Try to get the Access owner from the organization_id and person_id
- $access = null;
- if ($file->getOrganization() !== null && $file->getPerson() !== null) {
- $access = $this->accessRepository->findOneBy(
- ['organization' => $file->getOrganization(), 'person' => $file->getPerson()]
- );
- }
- $prefix = $this->getPrefix(
- $access ?? $file->getOrganization() ?? $file->getPerson(),
- $file->getIsTemporaryFile(),
- $file->getType()
- );
- $uid = date('Ymd_His').'_'.Uuid::uuid(5);
- $key = PathUtils::join($prefix, $uid, $file->getName());
- } else {
- $key = $file->getSlug();
- }
- if (!$isNewFile && !$this->filesystem->has($key)) {
- throw new \RuntimeException('The file `'.$key.'` does not exist in the file storage');
- }
- $size = $this->filesystem->write($key, $content, true);
- $file->setSize($size)
- ->setStatus(FileStatusEnum::READY);
- if ($isNewFile) {
- $file->setSlug($key)
- ->setCreateDate(new \DateTime())
- ->setCreatedBy($author->getId());
- } else {
- $file->setUpdateDate(new \DateTime())
- ->setUpdatedBy($author->getId());
- }
- $this->entityManager->flush();
- return $file;
- }
- /**
- * Convenient method to successively prepare and write a file.
- */
- public function makeFile(
- Organization|Access|Person $owner,
- string $filename,
- FileTypeEnum $type,
- string $content,
- Access $author,
- bool $isTemporary = false,
- FileVisibilityEnum $visibility = FileVisibilityEnum::NOBODY,
- ?string $mimeType = null,
- ?string $config = null,
- ?FileFolderEnum $folder = FileFolderEnum::UNRATED,
- ): File {
- $file = $this->prepareFile(
- $owner,
- $filename,
- $type,
- $author,
- $isTemporary,
- $visibility,
- $mimeType,
- false,
- $folder,
- );
- if (!empty($config)) {
- // TODO: Déplacer dans le prepareFile?
- $file->setConfig($config);
- }
- return $this->write($file, $content, $author);
- }
- /**
- * Uupdate the status of the File.
- */
- public function softDelete(File $file, Access $author): File
- {
- $file->setStatus(FileStatusEnum::DELETED)
- ->setSize(0)
- ->setUpdatedBy($author->getId());
- return $file;
- }
- /**
- * Delete the given file from the filesystem.
- */
- public function hardDelete(File $file): void
- {
- $deleted = $this->filesystem->delete($file->getSlug());
- if (!$deleted) {
- throw new \RuntimeException('File `'.$file->getSlug().'` could\'nt be deleted');
- }
- }
- /**
- * Permanently delete the entire file storage of the given Organization.
- */
- public function deleteOrganizationFiles(int $organizationId): void
- {
- $this->rrmDir('organization/'.$organizationId);
- $this->rrmDir('temp/organization/'.$organizationId);
- }
- /**
- * Permanently delete the entire file storage of the given Person.
- */
- public function deletePersonFiles(int $personId): void
- {
- $this->rrmDir('person/'.$personId);
- $this->rrmDir('temp/person/'.$personId);
- }
- /**
- * Supprime récursivement un répertoire.
- *
- * (Au moment du développement, Gaufrette ne permet pas la suppression de répertoires)
- */
- protected function rrmDir(string $dirKey): void
- {
- if (!$this->filesystem->isDirectory($dirKey)) {
- throw new \RuntimeException('Directory `'.$dirKey.'` does not exist');
- }
- $dir = PathUtils::join($this->fileStorageDir, $dirKey);
- $this->fileUtils->rmTree($dir);
- }
- /**
- * If an organization owns the file, the prefix will be '(_temp_/)organization/{id}(/{type})'.
- * If a person owns it, the prefix will be '(_temp_/)person/{id}(/{type})'
- * If access owns it, the prefix will be '(_temp_/)organization/{organization_id}/{access_id}(/{type})'.
- *
- * With {id} being the id of the organization or of the person.
- *
- * If the file is temporary, '_temp_/' is prepended to the prefix.
- * If a file type is given, this type is appended to the prefix (low case)
- */
- protected function getPrefix(
- Organization|Access|Person $owner,
- bool $isTemporary,
- ?FileTypeEnum $type = null,
- ): string {
- if ($owner instanceof Access) {
- $prefix = PathUtils::join('organization', $owner->getOrganization()?->getId(), $owner->getId());
- } elseif ($owner instanceof Organization) {
- $prefix = PathUtils::join('organization', $owner->getId());
- } else {
- $prefix = PathUtils::join('person', $owner->getId());
- }
- if ($isTemporary) {
- $prefix = PathUtils::join('temp', $prefix);
- }
- if ($type !== null && $type !== FileTypeEnum::NONE) {
- $prefix = PathUtils::join($prefix, strtolower($type->value));
- }
- return $prefix;
- }
- /**
- * Return an array [$organization, $person] from a given owner.
- *
- * @return list<Organization|Person|null>
- */
- #[Pure]
- protected function getOrganizationAndPersonFromOwner(Organization|Access|Person $owner): array
- {
- if ($owner instanceof Access) {
- return [$owner->getOrganization(), $owner->getPerson()];
- }
- if ($owner instanceof Organization) {
- return [$owner, null];
- }
- return [null, $owner];
- }
- public function support(File $file): bool
- {
- return $file->getHost() === FileHostEnum::AP2I;
- }
- }
|