LocalStorage.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service\Storage;
  4. use ApiPlatform\Core\Api\IriConverterInterface;
  5. use App\ApiResources\DownloadRequest;
  6. use App\Entity\Access\Access;
  7. use App\Entity\Core\File;
  8. use App\Entity\Organization\Organization;
  9. use App\Entity\Person\Person;
  10. use App\Enum\Core\FileStatusEnum;
  11. use App\Enum\Core\FileTypeEnum;
  12. use App\Repository\Access\AccessRepository;
  13. use App\Service\Utils\Path;
  14. use App\Service\Utils\Uuid;
  15. use DateTime;
  16. use Doctrine\ORM\EntityManagerInterface;
  17. use Gaufrette\Filesystem;
  18. use JetBrains\PhpStorm\Pure;
  19. use Knp\Bundle\GaufretteBundle\FilesystemMap;
  20. use Mimey\MimeTypes;
  21. use RuntimeException;
  22. /**
  23. * Read and write files into the file storage
  24. */
  25. class LocalStorage implements FileStorageInterface
  26. {
  27. /**
  28. * Key of the gaufrette storage, as defined in config/packages/knp_gaufrette.yaml
  29. */
  30. protected const FS_KEY = 'storage';
  31. protected Filesystem $filesystem;
  32. public function __construct(
  33. protected FilesystemMap $filesystemMap,
  34. protected EntityManagerInterface $entityManager,
  35. protected AccessRepository $accessRepository,
  36. protected IriConverterInterface $iriConverter
  37. )
  38. {
  39. $this->filesystem = $filesystemMap->get(static::FS_KEY);
  40. }
  41. /**
  42. * Return true if the file exists in the file storage
  43. *
  44. * @param File $file
  45. * @return bool
  46. */
  47. public function exists(File $file): bool {
  48. return $this->filesystem->has($file->getSlug());
  49. }
  50. /**
  51. * Get the IRI to download this file (eg: /api/download/1)
  52. *
  53. * @param File $file
  54. * @return string
  55. */
  56. public function getDownloadIri(File $file): string
  57. {
  58. return $this->iriConverter->getItemIriFromResourceClass(
  59. DownloadRequest::class,
  60. ['fileId' => $file->getId()]
  61. );
  62. }
  63. /**
  64. * Lists all the non-temporary files of the given owner
  65. *
  66. * @param Organization|Access|Person $owner
  67. * @param FileTypeEnum|null $type
  68. * @return array
  69. */
  70. public function listByOwner (
  71. Organization | Access | Person $owner,
  72. ?FileTypeEnum $type = null
  73. ): array {
  74. return $this->filesystem->listKeys(
  75. $this->getPrefix($owner, false, $type?->getValue())
  76. );
  77. }
  78. /**
  79. * Reads the given file and returns its content as a string
  80. *
  81. * @param File $file
  82. * @return string
  83. */
  84. public function read(File $file): string
  85. {
  86. return $this->filesystem->read($file->getSlug());
  87. }
  88. /**
  89. * Prepare a File record with a PENDING status.
  90. * This record will hold all the data needed to create the file, except its content.
  91. *
  92. * @param Organization|Access|Person $owner Owner of the file, either an organization, a person or both (access)
  93. * @param string $filename The file's name (mandatory)
  94. * @param FileTypeEnum $type The type of the new file
  95. * @param Access $createdBy Id of the access responsible for this creation
  96. * @param bool $isTemporary Is it a temporary file that can be deleted after some time
  97. * @param string|null $mimeType Mimetype of the file, if not provided, the method will try to guess it from its file name's extension
  98. * @param string $visibility
  99. * @param bool $flushFile Should the newly created file be flushed after having been persisted?
  100. * @return File
  101. */
  102. public function prepareFile(
  103. Organization | Access | Person $owner,
  104. string $filename,
  105. FileTypeEnum $type,
  106. Access $createdBy,
  107. bool $isTemporary = false,
  108. string $visibility = 'NOBODY',
  109. string $mimeType = null,
  110. bool $flushFile = true
  111. ): File
  112. {
  113. [$organization, $person] = $this->getOrganizationAndPersonFromOwner($owner);
  114. $file = (new File())
  115. ->setName($filename)
  116. ->setOrganization($organization)
  117. ->setPerson($person)
  118. ->setSlug(null)
  119. ->setType($type->getValue())
  120. ->setVisibility($visibility)
  121. ->setIsTemporaryFile($isTemporary)
  122. ->setMimeType($mimeType ?? self::guessMimeTypeFromFilename($filename))
  123. ->setCreateDate(new DateTime())
  124. ->setCreatedBy($createdBy->getId())
  125. ->setStatus(FileStatusEnum::PENDING()->getValue());
  126. $this->entityManager->persist($file);
  127. if ($flushFile) {
  128. $this->entityManager->flush();
  129. }
  130. return $file;
  131. }
  132. /**
  133. * Write the $content into the file storage and update the given File object's size, slug, status (READY)...
  134. *
  135. * @param File $file The file object that is about to be written
  136. * @param string $content The content of the file
  137. * @param Access $author The access responsible for the creation / update of the file
  138. * @return File
  139. */
  140. public function writeFile(File $file, string $content, Access $author): File
  141. {
  142. if (empty($file->getName())) {
  143. throw new RuntimeException('File has no filename');
  144. }
  145. $isNewFile = $file->getSlug() === null;
  146. if ($isNewFile) {
  147. // Try to get the Access owner from the organization_id and person_id
  148. $access = null;
  149. if ($file->getOrganization() !== null && $file->getPerson() !== null) {
  150. $access = $this->accessRepository->findOneBy(
  151. ['organization' => $file->getOrganization(), 'person' => $file->getPerson()]
  152. );
  153. }
  154. $prefix = $this->getPrefix(
  155. $access ?? $file->getOrganization() ?? $file->getPerson(),
  156. $file->getIsTemporaryFile(),
  157. $file->getType()
  158. );
  159. $uid = date('Ymd_His') . '_' . Uuid::uuid(5);
  160. $key = Path::join($prefix, $uid, $file->getName());
  161. } else {
  162. $key = $file->getSlug();
  163. }
  164. if (!$isNewFile && !$this->filesystem->has($key)) {
  165. throw new RuntimeException('The file `' . $key . '` does not exist in the file storage');
  166. }
  167. $size = $this->filesystem->write($key, $content, true);
  168. $file->setSize($size)
  169. ->setStatus(FileStatusEnum::READY()->getValue());
  170. if ($isNewFile) {
  171. $file->setSlug($key)
  172. ->setCreateDate(new DateTime())
  173. ->setCreatedBy($author->getId());
  174. } else {
  175. $file->setUpdateDate(new DateTime())
  176. ->setUpdatedBy($author->getId());
  177. }
  178. $this->entityManager->flush();
  179. return $file;
  180. }
  181. /**
  182. * Convenient method to successively prepare and write a file
  183. *
  184. * @param Organization|Access|Person $owner
  185. * @param string $filename
  186. * @param FileTypeEnum $type
  187. * @param string $content
  188. * @param Access $author
  189. * @param bool $isTemporary
  190. * @param string|null $mimeType
  191. * @param string $visibility
  192. * @return File
  193. */
  194. public function makeFile (
  195. Organization | Access | Person $owner,
  196. string $filename,
  197. FileTypeEnum $type,
  198. string $content,
  199. Access $author,
  200. bool $isTemporary = false,
  201. string $visibility = 'NOBODY',
  202. string $mimeType = null
  203. ): File
  204. {
  205. $file = $this->prepareFile(
  206. $owner,
  207. $filename,
  208. $type,
  209. $author,
  210. $isTemporary,
  211. $visibility,
  212. $mimeType,
  213. false
  214. );
  215. return $this->writeFile($file, $content, $author);
  216. }
  217. /**
  218. * Delete the given file from the filesystem and update the status of the File
  219. *
  220. * @param File $file
  221. * @param Access $author
  222. * @return File
  223. */
  224. public function delete(File $file, Access $author): File
  225. {
  226. $deleted = $this->filesystem->delete($file->getSlug());
  227. if (!$deleted) {
  228. throw new RuntimeException('File `' . $file->getSlug() . '` could\'nt be deleted');
  229. }
  230. $file->setStatus(FileStatusEnum::DELETED()->getValue())
  231. ->setSize(0)
  232. ->setUpdatedBy($author->getId());
  233. $this->entityManager->flush();
  234. return $file;
  235. }
  236. /**
  237. * Return the mimetype corresponding to the givent file extension
  238. *
  239. * @param string $ext
  240. * @return string|null
  241. */
  242. public static function getMimeTypeFromExt(string $ext): string | null {
  243. return (new MimeTypes)->getMimeType(ltrim($ext, '.'));
  244. }
  245. /**
  246. * Try to guess the mimetype from the filename
  247. *
  248. * Return null if it did not manage to guess it.
  249. *
  250. * @param string $filename
  251. * @return string|null
  252. */
  253. public static function guessMimeTypeFromFilename(string $filename): string | null {
  254. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  255. if (empty($ext)) {
  256. return null;
  257. }
  258. return self::getMimeTypeFromExt($ext);
  259. }
  260. /**
  261. * If an organization owns the file, the prefix will be '(_temp_/)organization/{id}(/{type})'.
  262. * If a person owns it, the prefix will be '(_temp_/)person/{id}(/{type})'
  263. * If access owns it, the prefix will be '(_temp_/)organization/{organization_id}/{access_id}(/{type})'
  264. *
  265. * With {id} being the id of the organization or of the person.
  266. *
  267. * If the file is temporary, '_temp_/' is prepended to the prefix.
  268. * If a file type is given, this type is appended to the prefix (low case)
  269. *
  270. * @param Organization|Access|Person $owner
  271. * @param bool $isTemporary
  272. * @param string|null $type
  273. * @return string
  274. */
  275. protected function getPrefix(
  276. Organization | Access | Person $owner,
  277. bool $isTemporary,
  278. string $type = null
  279. ): string
  280. {
  281. if ($owner instanceof Access) {
  282. $prefix = Path::join('organization', $owner->getOrganization()?->getId(), $owner->getId());
  283. } else if ($owner instanceof Organization) {
  284. $prefix = Path::join('organization', $owner->getId());
  285. } else {
  286. $prefix = Path::join('person', $owner->getId());
  287. }
  288. if ($isTemporary) {
  289. $prefix = Path::join('temp', $prefix);
  290. }
  291. if ($type !== null && $type !== FileTypeEnum::NONE()->getValue()) {
  292. $prefix = Path::join($prefix, strtolower($type));
  293. }
  294. return $prefix;
  295. }
  296. /**
  297. * Return an array [$organization, $person] from a given owner
  298. *
  299. * @param Organization|Access|Person $owner
  300. * @return array
  301. */
  302. #[Pure]
  303. protected function getOrganizationAndPersonFromOwner(Organization | Access | Person $owner): array {
  304. if ($owner instanceof Access) {
  305. return [$owner->getOrganization(), $owner->getPerson()];
  306. }
  307. if ($owner instanceof Organization) {
  308. return [$owner, null];
  309. }
  310. return [null, $owner];
  311. }
  312. }