<?php
namespace App\Database\Domain\Entity\User;
use App\Database\Domain\Entity\AbstractEntity;
use App\Infrastructure\Util\Identifier;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass="App\Database\Domain\Repository\AccessTokenRepository")
*/
class UserAccessToken extends AbstractEntity
{
/**
* @Assert\NotBlank()
*
* @ORM\Column(type="string", nullable=false)
*/
private string $token;
/**
* @ORM\ManyToOne(targetEntity="App\Database\Domain\Entity\User\User")
*
* @ORM\JoinColumn(nullable=false, onDelete="CASCADE")
*/
private UserInterface $user;
/**
* @ORM\Column(type="datetime_immutable", nullable=false)
*/
private \DateTimeInterface $expiresAt;
public function __construct(
string $id,
string $token,
UserInterface $user,
\DateTimeInterface $expiresAt
) {
$this->id = $id;
$this->token = $token;
$this->user = $user;
$this->expiresAt = $expiresAt;
}
public function getToken(): string
{
return $this->token;
}
public function setToken(string $token): self
{
$this->token = $token;
return $this;
}
public function getUser(): User
{
return $this->user;
}
public function setUser(User $user): self
{
$this->user = $user;
return $this;
}
public function getExpiresAt(): \DateTimeInterface
{
return $this->expiresAt;
}
public function extendExpires(\DateTimeInterface $dateTime)
{
$this->expiresAt = $dateTime;
}
public function isValid()
{
return $this->getExpiresAt()->getTimestamp() > (new \DateTimeImmutable('now'))->getTimestamp();
}
public static function twoMonths(UserInterface $user): self
{
return new self(Identifier::generate(),
bin2hex(random_bytes(24)), $user, new \DateTimeImmutable('now + 2 month'));
}
}