Skip to content

Commit

Permalink
Merge pull request #2 from aoirontec/trait-timestampable
Browse files Browse the repository at this point in the history
Add TimestampableTrait
  • Loading branch information
ddniel16 authored Dec 4, 2024
2 parents 0cca296 + ceaae68 commit d1f2cc1
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ Trait for doctrine entities
* [UpdateTrait](docs/UpdateTrait.md)
* [UserNameTrait](docs/UserNameTrait.md)
* [GetToFieldsTrait](docs/GetToFieldsTrait.md)
* [TimestampableTrait](docs/TimestampableTrait.md)
23 changes: 23 additions & 0 deletions docs/TimestampableTrait.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# TimestampableTrait

Trait para gestionar la fecha UTC de creación/actualización de una entidad.

````php
<?php

namespace App\Entity;

use \Irontec\DoctrineEntityTrait\TimestampableTrait;

class MyEntity
{
...
use TimestampableTrait;
...
}
````

# Fields

+ createdAt
+ updatedAt
52 changes: 52 additions & 0 deletions traits/TimestampableTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

/**
* This file is part of the DoctrineEntityTrait.
*/

namespace Irontec\DoctrineEntityTrait;

use DateTimeImmutable;
use DateTimeZone;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;

/**
* Entities using this Trait must have the
* `#[ORM\HasLifecycleCallbacks]` attribute.
*/
trait TimestampableTrait
{
#[ORM\Column(type: Types::DATETIME_IMMUTABLE, options: ['default' => 'CURRENT_TIMESTAMP'])]
#[Groups(['timestampable'])]
protected ?DateTimeImmutable $createdAt = null;

#[ORM\Column(type: Types::DATETIME_IMMUTABLE, options: ['default' => 'CURRENT_TIMESTAMP'])]
#[Groups(['timestampable'])]
protected ?DateTimeImmutable $updatedAt = null;

public function getCreatedAt(): ?DateTimeImmutable
{
return $this->createdAt;
}

public function getUpdatedAt(): ?DateTimeImmutable
{
return $this->updatedAt;
}

#[ORM\PrePersist]
public function createTimestamps(): void
{
$now = new DateTimeImmutable('now', timezone: new DateTimeZone('UTC'));
$this->createdAt = $now;
$this->updatedAt = $now;
}

#[ORM\PreUpdate]
public function updateTimestamps(): void
{
$this->updatedAt = new DateTimeImmutable('now', timezone: new DateTimeZone('UTC'));
}
}

0 comments on commit d1f2cc1

Please sign in to comment.