<?php
namespace App\Entity\User;
use App\Entity\Core\Institution;
use DateTime;
use DateTimeZone;
use Doctrine\ORM\Mapping as ORM;
use Exception;
#[ORM\Table('invitation')]
#[ORM\Entity]
class Invitation
{
const EXPIRES_AFTER = '24 hours';
#[ORM\Column(name: 'id', type: 'integer')]
#[ORM\Id]
#[ORM\GeneratedValue(strategy: 'AUTO')]
private int $id;
#[ORM\Column(name: 'token', type: 'string', length: 64)]
private string $token;
#[ORM\Column(name: 'email', type: 'string', length: 255)]
private string $email;
#[ORM\JoinColumn(name: 'issued_by', referencedColumnName: 'id', onDelete: 'SET NULL', nullable: true)]
#[ORM\ManyToOne(targetEntity: User::class)]
private ?User $issuedBy;
#[ORM\Column(name: 'created', type: 'datetime')]
private DateTime $created;
#[ORM\Column(name: 'active', type: 'boolean')]
private bool $active;
#[ORM\Column(name: 'role', type: 'string', length: 32)]
private string $role;
#[ORM\JoinColumn(name: 'institution', referencedColumnName: 'id', onDelete: 'CASCADE', nullable: false)]
#[ORM\ManyToOne(targetEntity: Institution::class)]
private Institution $institution;
public function getId(): ?int
{
return $this->id ?? null; // To avoid property access error in EasyAdmin
}
public function setId(int $id): void
{
$this->id = $id;
}
public function getToken(): string
{
return $this->token;
}
public function setToken(string $token): void
{
$this->token = $token;
}
public function getEmail(): string
{
return $this->email;
}
public function setEmail(string $email): void
{
$this->email = $email;
}
public function getIssuedBy(): ?User
{
return $this->issuedBy;
}
public function setIssuedBy(?User $issuedBy): void
{
$this->issuedBy = $issuedBy;
}
public function getCreated(): DateTime
{
return $this->created;
}
public function setCreated(DateTime $created): void
{
$this->created = $created;
}
public function isActive(): bool
{
return $this->active;
}
public function setActive(bool $active): void
{
$this->active = $active;
}
public function getRole(): string
{
return $this->role;
}
public function setRole(string $role): void
{
$this->role = $role;
}
public function getInstitution(): Institution
{
return $this->institution;
}
public function setInstitution(Institution $institution): void
{
$this->institution = $institution;
}
/**
* @throws Exception
*/
public function isValid(): bool
{
if (!$this->isActive()) {
return false;
}
$latestCreationTime = new DateTime('-' . self::EXPIRES_AFTER, new DateTimeZone('Europe/Copenhagen'));
if ($this->getCreated() < $latestCreationTime) {
return false;
}
if ($this->getIssuedBy() === null) {
return false;
}
return true;
}
/**
* @throws Exception
*/
public function generateToken(): void
{
$this->token = bin2hex(random_bytes(20));
}
}