LocalStorage.php 12 KB

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