src/Entity/ImageS.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Entity;
  3. use App\Repository\ImageSRepository;
  4. use Doctrine\ORM\Mapping as ORM;
  5. use Symfony\Component\HttpFoundation\File\UploadedFile;
  6. use Symfony\Component\Validator\Constraints as Assert;
  7. #[ORM\Entity(repositoryClass: ImageSRepository::class)]
  8. #[ORM\HasLifecycleCallbacks]
  9. #[ORM\Table(name: "ImageS")]
  10. class ImageS
  11. {
  12. #[ORM\Id]
  13. #[ORM\GeneratedValue]
  14. #[ORM\Column(type: "integer")]
  15. private ?int $id = null;
  16. #[ORM\Column(type: "string", length: 255)]
  17. private ?string $url = null;
  18. #[ORM\Column(type: "string", length: 255)]
  19. private ?string $alt = null;
  20. private ?UploadedFile $file = null;
  21. private ?string $tempFilename = null;
  22. public function getId(): ?int
  23. {
  24. return $this->id;
  25. }
  26. public function getUrl(): ?string
  27. {
  28. return $this->url;
  29. }
  30. public function setUrl(string $url): self
  31. {
  32. $this->url = $url;
  33. return $this;
  34. }
  35. public function getAlt(): ?string
  36. {
  37. return $this->alt;
  38. }
  39. public function setAlt(string $alt): self
  40. {
  41. $this->alt = $alt;
  42. return $this;
  43. }
  44. public function getFile(): ?UploadedFile
  45. {
  46. return $this->file;
  47. }
  48. public function setFile(UploadedFile $file): self
  49. {
  50. $this->file = $file;
  51. if (null !== $this->url) {
  52. $this->tempFilename = $this->url;
  53. $this->url = null;
  54. $this->alt = null;
  55. }
  56. return $this;
  57. }
  58. #[ORM\PrePersist]
  59. #[ORM\PreUpdate]
  60. public function preUpload(): void
  61. {
  62. if (null === $this->file) {
  63. return;
  64. }
  65. $name = $this->file->getClientOriginalName();
  66. $this->url = $name;
  67. $this->alt = $name;
  68. }
  69. #[ORM\PostPersist]
  70. #[ORM\PostUpdate]
  71. public function upload(): void
  72. {
  73. if (null === $this->file) {
  74. return;
  75. }
  76. if (null !== $this->tempFilename) {
  77. $oldFile = $this->getUploadRootDir() . '/' . $this->tempFilename;
  78. if (file_exists($oldFile)) {
  79. unlink($oldFile);
  80. }
  81. }
  82. $this->file->move($this->getUploadRootDir(), $this->url);
  83. }
  84. #[ORM\PreRemove]
  85. public function preRemoveUpload(): void
  86. {
  87. $this->tempFilename = $this->getUploadRootDir() . '/' . $this->url;
  88. }
  89. #[ORM\PostRemove]
  90. public function removeUpload(): void
  91. {
  92. if (file_exists($this->tempFilename)) {
  93. unlink($this->tempFilename);
  94. }
  95. }
  96. public function getUploadDir(): string
  97. {
  98. return 'uploads/img';
  99. }
  100. public function getUploadRootDir(): string
  101. {
  102. // Adapte ce chemin à Symfony 5 (le répertoire "web/" n'existe plus)
  103. return __DIR__ . '/../../public/' . $this->getUploadDir();
  104. }
  105. }