Advertisement
Guest User

Untitled

a guest
Jun 26th, 2024
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.50 KB | Source Code | 0 0
  1. <?php
  2.  
  3. namespace App\Entity\Traits;
  4.  
  5. use DateTime;
  6. use DateTimeInterface;
  7. use Doctrine\DBAL\Types\Types;
  8. use Exception;
  9. use Doctrine\ORM\Mapping as ORM;
  10.  
  11. trait TimestampTrait
  12. {
  13.     #[ORM\Column(type: Types::DATETIME_IMMUTABLE, nullable: true)]
  14.    private ?DateTime $createdAt = null;
  15.  
  16.     #[ORM\Column(type: Types::DATETIME_IMMUTABLE, nullable: true)]
  17.    private ?DateTime $updatedAt = null;
  18.  
  19.     /**
  20.      * @return DateTimeInterface|null
  21.      * @throws Exception
  22.      */
  23.     public function getCreatedAt(): ?DateTimeInterface
  24.     {
  25.         return $this->createdAt ?? new DateTime();
  26.     }
  27.  
  28.     /**
  29.      * @param DateTimeInterface $createdAt
  30.      * @return $this
  31.      */
  32.     public function setCreatedAt(DateTimeInterface $createdAt): self
  33.     {
  34.         $this->createdAt = $createdAt;
  35.  
  36.         return $this;
  37.     }
  38.  
  39.     /**
  40.      * @return DateTimeInterface|null
  41.      */
  42.     public function getUpdatedAt(): ?DateTimeInterface
  43.     {
  44.         return $this->updatedAt ?? new DateTime();
  45.     }
  46.  
  47.     /**
  48.      * @param DateTimeInterface $updatedAt
  49.      * @return $this
  50.      */
  51.     public function setUpdatedAt(DateTimeInterface $updatedAt): self
  52.     {
  53.         $this->updatedAt = $updatedAt;
  54.  
  55.         return $this;
  56.     }
  57.  
  58.     #[ORM\PrePersist]
  59.    #[ORM\PreUpdate]
  60.    public function updateTimestamps(): void
  61.     {
  62.         $now = new DateTime();
  63.         $this->setUpdatedAt($now);
  64.         if ($this->getId() === null) {
  65.             $this->setCreatedAt($now);
  66.         }
  67.     }
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement