LocalStorage.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service\File\Storage;
  4. use App\Entity\Access\Access;
  5. use App\Entity\Core\File;
  6. use App\Entity\Organization\Organization;
  7. use App\Entity\Person\Person;
  8. use App\Enum\Core\FileFolderEnum;
  9. use App\Enum\Core\FileHostEnum;
  10. use App\Enum\Core\FileSizeEnum;
  11. use App\Enum\Core\FileStatusEnum;
  12. use App\Enum\Core\FileTypeEnum;
  13. use App\Enum\Core\FileVisibilityEnum;
  14. use App\Repository\Access\AccessRepository;
  15. use App\Service\File\Factory\ImageFactory;
  16. use App\Service\Utils\FileUtils;
  17. use App\Service\Utils\PathUtils;
  18. use App\Service\Utils\UrlBuilder;
  19. use App\Service\Utils\Uuid;
  20. use Doctrine\ORM\EntityManagerInterface;
  21. use Gaufrette\FilesystemInterface;
  22. use JetBrains\PhpStorm\Pure;
  23. use Knp\Bundle\GaufretteBundle\FilesystemMap;
  24. use Liip\ImagineBundle\Imagine\Cache\CacheManager;
  25. use Liip\ImagineBundle\Imagine\Data\DataManager;
  26. /**
  27. * Read and write files into the file storage.
  28. */
  29. class LocalStorage implements FileStorageInterface
  30. {
  31. /**
  32. * Key of the gaufrette storage, as defined in config/packages/knp_gaufrette.yaml.
  33. */
  34. protected const FS_KEY = 'storage';
  35. // Cache Image Folder
  36. protected const SM_FOLDER = 'sm';
  37. protected const MD_FOLDER = 'md';
  38. protected const LG_FOLDER = 'lg';
  39. protected const CROP_SM = 'crop_sm';
  40. protected const CROP_MD = 'crop_md';
  41. protected const CROP_LG = 'crop_lg';
  42. protected FilesystemInterface $filesystem;
  43. public function __construct(
  44. protected readonly FilesystemMap $filesystemMap,
  45. protected readonly EntityManagerInterface $entityManager,
  46. protected readonly AccessRepository $accessRepository,
  47. protected readonly DataManager $dataManager,
  48. protected readonly CacheManager $cacheManager,
  49. protected readonly ImageFactory $imageFactory,
  50. protected readonly FileUtils $fileUtils,
  51. protected readonly UrlBuilder $urlBuilder,
  52. protected readonly string $fileStorageDir,
  53. ) {
  54. $this->filesystem = $filesystemMap->get(static::FS_KEY);
  55. }
  56. /**
  57. * Return true if the file exists in the file storage.
  58. */
  59. public function exists(File $file): bool
  60. {
  61. return $this->filesystem->has($file->getSlug());
  62. }
  63. /**
  64. * Lists all the non-temporary files of the given owner.
  65. *
  66. * @return list<string>
  67. */
  68. public function listByOwner(
  69. Organization|Access|Person $owner,
  70. ?FileTypeEnum $type = null,
  71. ): array {
  72. return $this->filesystem->listKeys(
  73. $this->getPrefix($owner, false, $type)
  74. );
  75. }
  76. /**
  77. * Reads the given file and returns its content as a string.
  78. */
  79. public function read(File $file): string
  80. {
  81. return $this->filesystem->read($file->getSlug());
  82. }
  83. /**
  84. * Retourne l'URL de l'image, à la bonne taille, contenu dans le File.
  85. */
  86. public function getImageUrl(File $file, string $size, bool $relativePath, bool $uncropped = false): string
  87. {
  88. $crop = !empty($file->getConfig()) && !$uncropped;
  89. $filterName = $this->getFilterFromSizeAndConfig($size, $crop);
  90. $path = $file->getSlug();
  91. if (!$this->cacheManager->isStored($path, $filterName)) {
  92. try {
  93. $this->imageFactory->createImageContent($file, $filterName, $uncropped);
  94. } catch (\Exception $e) {
  95. $path = 'images/missing-file.png';
  96. return $relativePath ? $path : $this->urlBuilder->getAbsoluteUrl($path);
  97. }
  98. }
  99. $url = $this->cacheManager->resolve($path, $filterName);
  100. return $relativePath ? $this->urlBuilder->getRelativeUrl($url) : $url;
  101. }
  102. /**
  103. * Retourne le filtre Liip correspondant à la taille désirée.
  104. */
  105. protected function getFilterFromSizeAndConfig(string $size, bool $crop = true): string
  106. {
  107. switch ($size) {
  108. case FileSizeEnum::SM->value :
  109. $filter = $crop ? self::CROP_SM : self::SM_FOLDER;
  110. break;
  111. case FileSizeEnum::MD->value :
  112. default:
  113. $filter = $crop ? self::CROP_MD : self::MD_FOLDER;
  114. break;
  115. case FileSizeEnum::LG->value :
  116. $filter = $crop ? self::CROP_LG : self::LG_FOLDER;
  117. break;
  118. }
  119. return $filter;
  120. }
  121. /**
  122. * Prepare a File record with a PENDING status.
  123. * This record will hold all the data needed to create the file, except its content.
  124. *
  125. * @param Organization|Access|Person $owner Owner of the file, either an organization, a person or both (access)
  126. * @param string $filename The file's name (mandatory)
  127. * @param FileTypeEnum $type The type of the new file
  128. * @param Access $createdBy Id of the access responsible for this creation
  129. * @param bool $isTemporary Is it a temporary file that can be deleted after some time
  130. * @param string|null $mimeType Mimetype of the file, if not provided, the method will try to guess it from its file name's extension
  131. * @param bool $flushFile Should the newly created file be flushed after having been persisted?
  132. * @param FileFolderEnum|null $folder The folder where the file is stored, designed for document management
  133. */
  134. public function prepareFile(
  135. Organization|Access|Person $owner,
  136. string $filename,
  137. FileTypeEnum $type,
  138. Access $createdBy,
  139. bool $isTemporary = false,
  140. FileVisibilityEnum $visibility = FileVisibilityEnum::NOBODY,
  141. ?string $mimeType = null,
  142. bool $flushFile = true,
  143. ?FileFolderEnum $folder = FileFolderEnum::UNRATED,
  144. ): File {
  145. [$organization, $person] = $this->getOrganizationAndPersonFromOwner($owner);
  146. $file = (new File())
  147. ->setName($filename)
  148. ->setSlug(null)
  149. ->setOrganization($organization)
  150. ->setPerson($person)
  151. ->setType($type)
  152. ->setVisibility($visibility)
  153. ->setIsTemporaryFile($isTemporary)
  154. ->setMimeType($mimeType ?? $this->fileUtils->guessMimeTypeFromFilename($filename))
  155. ->setCreateDate(new \DateTime())
  156. ->setCreatedBy($createdBy->getId())
  157. ->setFolder($folder)
  158. ->setStatus(FileStatusEnum::PENDING);
  159. $this->entityManager->persist($file);
  160. if ($flushFile) {
  161. $this->entityManager->flush();
  162. }
  163. return $file;
  164. }
  165. /**
  166. * Write the $content into the file storage and update the given File object's size, slug, status (READY)...
  167. *
  168. * @param File $file The file object that is about to be written
  169. * @param string $content The content of the file
  170. * @param Access $author The access responsible for the creation / update of the file
  171. */
  172. public function write(File $file, string $content, Access $author): File
  173. {
  174. if (empty($file->getName())) {
  175. throw new \RuntimeException('File has no filename');
  176. }
  177. try {
  178. $isNewFile = $file->getSlug() === null;
  179. } catch (\Throwable) {
  180. $isNewFile = true; // Catch case where slud has not been initialized
  181. }
  182. if ($isNewFile) {
  183. // Try to get the Access owner from the organization_id and person_id
  184. $access = null;
  185. if ($file->getOrganization() !== null && $file->getPerson() !== null) {
  186. $access = $this->accessRepository->findOneBy(
  187. ['organization' => $file->getOrganization(), 'person' => $file->getPerson()]
  188. );
  189. }
  190. $prefix = $this->getPrefix(
  191. $access ?? $file->getOrganization() ?? $file->getPerson(),
  192. $file->getIsTemporaryFile(),
  193. $file->getType()
  194. );
  195. $uid = date('Ymd_His').'_'.Uuid::uuid(5);
  196. $key = PathUtils::join($prefix, $uid, $file->getName());
  197. } else {
  198. $key = $file->getSlug();
  199. }
  200. if (!$isNewFile && !$this->filesystem->has($key)) {
  201. throw new \RuntimeException('The file `'.$key.'` does not exist in the file storage');
  202. }
  203. $size = $this->filesystem->write($key, $content, true);
  204. $file->setSize($size)
  205. ->setStatus(FileStatusEnum::READY);
  206. if ($isNewFile) {
  207. $file->setSlug($key)
  208. ->setCreateDate(new \DateTime())
  209. ->setCreatedBy($author->getId());
  210. } else {
  211. $file->setUpdateDate(new \DateTime())
  212. ->setUpdatedBy($author->getId());
  213. }
  214. $this->entityManager->flush();
  215. return $file;
  216. }
  217. /**
  218. * Convenient method to successively prepare and write a file.
  219. */
  220. public function makeFile(
  221. Organization|Access|Person $owner,
  222. string $filename,
  223. FileTypeEnum $type,
  224. string $content,
  225. Access $author,
  226. bool $isTemporary = false,
  227. FileVisibilityEnum $visibility = FileVisibilityEnum::NOBODY,
  228. ?string $mimeType = null,
  229. ?string $config = null,
  230. ?FileFolderEnum $folder = FileFolderEnum::UNRATED,
  231. ): File {
  232. $file = $this->prepareFile(
  233. $owner,
  234. $filename,
  235. $type,
  236. $author,
  237. $isTemporary,
  238. $visibility,
  239. $mimeType,
  240. false,
  241. $folder,
  242. );
  243. if (!empty($config)) {
  244. // TODO: Déplacer dans le prepareFile?
  245. $file->setConfig($config);
  246. }
  247. return $this->write($file, $content, $author);
  248. }
  249. /**
  250. * Uupdate the status of the File.
  251. */
  252. public function softDelete(File $file, Access $author): File
  253. {
  254. $file->setStatus(FileStatusEnum::DELETED)
  255. ->setSize(0)
  256. ->setUpdatedBy($author->getId());
  257. return $file;
  258. }
  259. /**
  260. * Delete the given file from the filesystem.
  261. */
  262. public function hardDelete(File $file): void
  263. {
  264. $deleted = $this->filesystem->delete($file->getSlug());
  265. if (!$deleted) {
  266. throw new \RuntimeException('File `'.$file->getSlug().'` could\'nt be deleted');
  267. }
  268. }
  269. /**
  270. * Permanently delete the entire file storage of the given Organization.
  271. */
  272. public function deleteOrganizationFiles(int $organizationId): void
  273. {
  274. $this->rrmDir('organization/'.$organizationId);
  275. $this->rrmDir('temp/organization/'.$organizationId);
  276. }
  277. /**
  278. * Permanently delete the entire file storage of the given Person.
  279. */
  280. public function deletePersonFiles(int $personId): void
  281. {
  282. $this->rrmDir('person/'.$personId);
  283. $this->rrmDir('temp/person/'.$personId);
  284. }
  285. /**
  286. * Supprime récursivement un répertoire.
  287. *
  288. * (Au moment du développement, Gaufrette ne permet pas la suppression de répertoires)
  289. */
  290. protected function rrmDir(string $dirKey): void
  291. {
  292. if (!$this->filesystem->isDirectory($dirKey)) {
  293. throw new \RuntimeException('Directory `'.$dirKey.'` does not exist');
  294. }
  295. $dir = PathUtils::join($this->fileStorageDir, $dirKey);
  296. $this->fileUtils->rmTree($dir);
  297. }
  298. /**
  299. * If an organization owns the file, the prefix will be '(_temp_/)organization/{id}(/{type})'.
  300. * If a person owns it, the prefix will be '(_temp_/)person/{id}(/{type})'
  301. * If access owns it, the prefix will be '(_temp_/)organization/{organization_id}/{access_id}(/{type})'.
  302. *
  303. * With {id} being the id of the organization or of the person.
  304. *
  305. * If the file is temporary, '_temp_/' is prepended to the prefix.
  306. * If a file type is given, this type is appended to the prefix (low case)
  307. */
  308. protected function getPrefix(
  309. Organization|Access|Person $owner,
  310. bool $isTemporary,
  311. ?FileTypeEnum $type = null,
  312. ): string {
  313. if ($owner instanceof Access) {
  314. $prefix = PathUtils::join('organization', $owner->getOrganization()?->getId(), $owner->getId());
  315. } elseif ($owner instanceof Organization) {
  316. $prefix = PathUtils::join('organization', $owner->getId());
  317. } else {
  318. $prefix = PathUtils::join('person', $owner->getId());
  319. }
  320. if ($isTemporary) {
  321. $prefix = PathUtils::join('temp', $prefix);
  322. }
  323. if ($type !== null && $type !== FileTypeEnum::NONE) {
  324. $prefix = PathUtils::join($prefix, strtolower($type->value));
  325. }
  326. return $prefix;
  327. }
  328. /**
  329. * Return an array [$organization, $person] from a given owner.
  330. *
  331. * @return list<Organization|Person|null>
  332. */
  333. #[Pure]
  334. protected function getOrganizationAndPersonFromOwner(Organization|Access|Person $owner): array
  335. {
  336. if ($owner instanceof Access) {
  337. return [$owner->getOrganization(), $owner->getPerson()];
  338. }
  339. if ($owner instanceof Organization) {
  340. return [$owner, null];
  341. }
  342. return [null, $owner];
  343. }
  344. public function support(File $file): bool
  345. {
  346. return $file->getHost() === FileHostEnum::AP2I;
  347. }
  348. }