LocalStorage.php 11 KB

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