src/Entity/FichierAdmin.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\Entity;
  3. use App\Repository\FichierRepository;
  4. use Doctrine\DBAL\Types\Types;
  5. use Doctrine\ORM\Mapping as ORM;
  6. use Doctrine\ORM\Mapping\Table;
  7. use Gedmo\Mapping\Annotation as Gedmo;
  8. use Symfony\Component\HttpFoundation\File\UploadedFile;
  9. use Symfony\Component\Validator\Constraints as Assert;
  10. use Symfony\Component\Serializer\Annotation\Groups as Group;
  11. #[ORM\Entity(repositoryClassFichierRepository::class)]
  12. #[Table(name'_admin_param_fichier')]
  13. #[ORM\HasLifecycleCallbacks]
  14. class FichierAdmin
  15. {
  16.     const DEFAULT_MIME_TYPES = [
  17.         'text/plain''application/octet-stream''application/pdf''application/vnd.ms-excel''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet''application/msword''application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  18.     ];
  19.     #[ORM\Id]
  20.     #[ORM\GeneratedValue]
  21.     #[ORM\Column]
  22.     #[Group(["fichier"])]
  23.     private ?int $id null;
  24.     #[ORM\Column(nullabletrue)]
  25.     private ?int $size null;
  26.     #[ORM\Column(length255nullabletrue)]
  27.     #[Group(["fichier"])]
  28.     private ?string $path null;
  29.     #[ORM\Column(length255nullabletrue)]
  30.     #[Group(["fichier"])]
  31.     private ?string $alt null;
  32.     #[ORM\Column(typeTypes::DATETIME_MUTABLE)]
  33.     #[Gedmo\Timestampable(on'create')]
  34.     private ?\DateTimeInterface $dateCreation null;
  35.     #[ORM\Column(length5nullabletrue)]
  36.     #[Group(["fichier"])]
  37.     private ?string $url null;
  38.     #[Assert\NotNull(message"Veuillez sélectionner un fichier"groups: ["FileRequired"])]
  39.     private  $file;
  40.     private ?string $verifieIfeditEmployeDocument null;
  41.     /**
  42.      * @return string|null
  43.      */
  44.     public function getVerifieIfeditEmployeDocument()
  45.     {
  46.         return $this->verifieIfeditEmployeDocument;
  47.     }
  48.     /**
  49.      * @param string|null $verifieIfeditEmployeDocument
  50.      */
  51.     public function setVerifieIfeditEmployeDocument($verifieIfeditEmployeDocument)
  52.     {
  53.         $this->verifieIfeditEmployeDocument $verifieIfeditEmployeDocument;
  54.     }
  55.     /**
  56.      * @var string
  57.      */
  58.     private $uploadDir;
  59.     private $filePrefix '';
  60.     /**
  61.      * @var mixed
  62.      */
  63.     private $tempFilename;
  64.     public function getFile(): ?string
  65.     {
  66.         return $this->file;
  67.     }
  68.     public function __construct()
  69.     {
  70.         //$this->path = "media_entreprise";
  71.     }
  72.     // On modifie le setter de File, pour prendre en compte l'upload d'un fichier lorsqu'il en existe déjà un autre
  73.     /**
  74.      * @param UploadedFile|null $file
  75.      */
  76.     public function setFile(UploadedFile $file null)
  77.     {
  78.         $this->file $file;
  79.         // On vérifie si on avait déjà un fichier pour cette entité
  80.         if (null !== $this->alt && $file) {
  81.             // On sauvegarde l'extension du fichier pour le supprimer plus tard
  82.             $this->tempFilename $this->alt;
  83.             // On réinitialise les valeurs des attributs url et alt
  84.             $this->url null;
  85.             $this->alt null;
  86.             $this->size 0;
  87.         }
  88.     }
  89.     #[ORM\PrePersist()]
  90.     #[ORM\PreUpdate()]
  91.     public function preUpload()
  92.     {
  93.         // dd($this->size);
  94.         // Si jamais il n'y a pas de fichier (champ facultatif)
  95.         if (null === $this->file) {
  96.             //dump('foo00');exit;
  97.             return false;
  98.         }
  99.         //dump('foo');exit;
  100.         // dd("jljklme");
  101.         // Le nom du fichier est son id, on doit juste stocker également son extension
  102.         // Pour faire propre, on devrait renommer cet attribut en « extension », plutôt que « url »
  103.         //$this->url = $this->file->guessExtension();
  104.         $clientOriginalName $this->file->getClientOriginalName();
  105.         $fileExt  pathinfo($clientOriginalNamePATHINFO_EXTENSION);
  106.         $baseName $this->filePrefix '_' pathinfo($clientOriginalNamePATHINFO_FILENAME);
  107.         $this->url $fileExt;
  108.         // Et on génère l'attribut alt de la balise <img>, à la valeur du nom du fichier sur le PC de l'internaute
  109.         $this->alt substr(str_slug($baseName'_'), 0255 strlen($fileExt)) . '.' $fileExt;
  110.         $this->size      $this->file->getSize();
  111.     }
  112.     #[ORM\PrePersist()]
  113.     #[ORM\PreUpdate()]
  114.     public function upload()
  115.     {
  116.         $uploadDir $this->getUploadRootDir();
  117.         // Si jamais il n'y a pas de fichier (champ facultatif)t
  118.         if (null === $this->file) {
  119.             return;
  120.         }
  121.         // Si on avait un ancien fichier, on le supprime
  122.         if (null !== $this->tempFilename) {
  123.             $file $this->getFullFileName();
  124.             if (file_exists($file)) {
  125.                 unlink($file);
  126.             }
  127.         }
  128.         //dump($this->alt, $this->getFullPath());exit;
  129.         $this->file->move(
  130.             $this->getFullPath(), // Le répertoire de destination
  131.             $this->alt
  132.         );
  133.         // On libère le fichier pour éviter l'erreur de sérialisation (Serialization of UploadedFile is not allowed)
  134.         $this->file null;
  135.         // On déplace le fichier envoyé dans le répertoire de notre choix
  136.     }
  137.     #[ORM\PreRemove()]
  138.     public function preRemoveUpload()
  139.     {
  140.         // On sauvegarde temporairement le nom du fichier, car il dépend de l'id
  141.         $this->tempFilename $this->getFullFileName();
  142.     }
  143.     #[ORM\PreRemove()]
  144.     public function removeUpload()
  145.     {
  146.         if ($this->getUrl() == 'link') {
  147.             return;
  148.         }
  149.         // En PostRemove, on n'a pas accès à l'id, on utilise notre nom sauvegardé
  150.         if (file_exists($this->tempFilename)) {
  151.             // On supprime le fichier
  152.             unlink($this->tempFilename);
  153.         }
  154.     }
  155.     /**
  156.      * @param $uploadDir
  157.      * @return mixed
  158.      */
  159.     public function setUploadDir($uploadDir)
  160.     {
  161.         if (!is_dir($uploadDir)) {
  162.             mkdir($uploadDir0777true);
  163.         }
  164.         $this->uploadDir $uploadDir;
  165.         return $this;
  166.     }
  167.     public function getId(): ?int
  168.     {
  169.         return $this->id;
  170.     }
  171.     public function getSize(): ?int
  172.     {
  173.         return $this->size;
  174.     }
  175.     public function setSize(int $size): self
  176.     {
  177.         if ($this->getSize() !== null) {
  178.             $this->size $size;
  179.         } else {
  180.             $this->size 0;
  181.         }
  182.         return $this;
  183.     }
  184.     public function getPath(): ?string
  185.     {
  186.         return $this->path;
  187.     }
  188.     public function setPath(string $path): self
  189.     {
  190.         $this->path $path;
  191.         return $this;
  192.     }
  193.     public function getAlt(): ?string
  194.     {
  195.         return $this->alt;
  196.     }
  197.     public function setAlt(string $alt): self
  198.     {
  199.         $this->alt $alt;
  200.         return $this;
  201.     }
  202.     public function getDateCreation(): ?\DateTimeInterface
  203.     {
  204.         return $this->dateCreation;
  205.     }
  206.     public function setDateCreation(\DateTimeInterface $dateCreation): self
  207.     {
  208.         $this->dateCreation $dateCreation;
  209.         return $this;
  210.     }
  211.     /**
  212.      * @return mixed
  213.      */
  214.     public function getUploadDir()
  215.     {
  216.         // On retourne le chemin relatif vers l'image pour un navigateur
  217.         return $this->uploadDir ?: 'uploads';
  218.     }
  219.     protected function getUploadRootDir()
  220.     {
  221.         // On retourne le chemin relatif vers l'image pour notre code PHP
  222.         return __DIR__ '/../../public/' $this->getUploadDir();
  223.     }
  224.     public function getWebPath()
  225.     {
  226.         return @$this->getFullFileName();
  227.     }
  228.     public function getFileNamePath()
  229.     {
  230.         return 'uploads/' $this->getPath() . '/' $this->getFileName();
  231.     }
  232.     public function getFileName()
  233.     {
  234.         return basename($this->getFullFileName());
  235.     }
  236.     protected function getUploadBaseDir()
  237.     {
  238.         // On retourne le chemin relatif vers l'image pour notre code PHP
  239.         return __DIR__ '/../../public/uploads/';
  240.     }
  241.     /**
  242.      * @return mixed
  243.      */
  244.     public function getFullPath()
  245.     {
  246.         return $this->getUploadBaseDir() . $this->getPath();
  247.     }
  248.     /**
  249.      * @return mixed
  250.      */
  251.     public function getFullFileName()
  252.     {
  253.         if ($this->getUrl() != 'link') {
  254.             $fileName file_exists($this->getFullPath() . '/' $this->alt) ?
  255.                 $this->getFullPath() . '/' $this->alt :
  256.                 $this->getFullPath() . '/' $this->id '.' $this->url;
  257.         } else {
  258.             $fileName $this->getAlt();
  259.         }
  260.         return $fileName;
  261.     }
  262.     public function getUrl(): ?string
  263.     {
  264.         return $this->url;
  265.     }
  266.     public function setUrl(string $url): self
  267.     {
  268.         $this->url $url;
  269.         return $this;
  270.     }
  271.     /**
  272.      * Get the value of filePrefix
  273.      */
  274.     public function getFilePrefix()
  275.     {
  276.         return $this->filePrefix;
  277.     }
  278.     /**
  279.      * Set the value of filePrefix
  280.      *
  281.      * @return  self
  282.      */
  283.     public function setFilePrefix($filePrefix)
  284.     {
  285.         $this->filePrefix $filePrefix;
  286.         return $this;
  287.     }
  288.     public function __serialize(): array
  289.     {
  290.         return [
  291.             'id' => $this->id,
  292.             'size' => $this->size,
  293.             'path' => $this->path,
  294.             'alt' => $this->alt,
  295.             'dateCreation' => $this->dateCreation,
  296.             'url' => $this->url,
  297.             'verifieIfeditEmployeDocument' => $this->verifieIfeditEmployeDocument,
  298.             'uploadDir' => $this->uploadDir,
  299.             'filePrefix' => $this->filePrefix,
  300.             'tempFilename' => $this->tempFilename,
  301.         ];
  302.     }
  303.     public function __unserialize(array $data): void
  304.     {
  305.         $this->id $data['id'] ?? null;
  306.         $this->size $data['size'] ?? null;
  307.         $this->path $data['path'] ?? null;
  308.         $this->alt $data['alt'] ?? null;
  309.         $this->dateCreation $data['dateCreation'] ?? null;
  310.         $this->url $data['url'] ?? null;
  311.         $this->verifieIfeditEmployeDocument $data['verifieIfeditEmployeDocument'] ?? null;
  312.         $this->uploadDir $data['uploadDir'] ?? null;
  313.         $this->filePrefix $data['filePrefix'] ?? '';
  314.         $this->tempFilename $data['tempFilename'] ?? null;
  315.     }
  316. }