<?php
namespace App\Entity;
use App\Service\Helper\DateTimeHelper;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Exception;
/**
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
* @ORM\Table(name="users__users",
* indexes={
* @ORM\Index(name="password", columns={"password"})
* })
*/
class User
{
use IdTrait;
/**
* @ORM\Column(name="created_at", type="datetime", nullable=false)
*/
private DateTime $createdAt;
/**
* @ORM\Column(name="phone", type="string", nullable=false, unique=true)
*/
private string $phone;
/**
* @ORM\Column(name="password", type="string", nullable=false)
*/
private string $password;
/**
* @ORM\Column(name="cookie", type="string", nullable=false)
*/
private string $cookie;
/**
* @var Collection|UserRole[]
*
* @ORM\OneToMany(targetEntity="App\Entity\UserRole", mappedBy="user")
*/
private $roles;
/**
* @ORM\OneToOne(targetEntity="App\Entity\Cart", mappedBy="user")
*/
private ?Cart $cart = null;
/**
* @ORM\OneToOne(targetEntity="Manager", mappedBy="user")
*/
private ?Manager $manager = null;
/**
* @throws Exception
*/
public function __construct(string $phone, string $password)
{
$this->createdAt = DateTimeHelper::getNowDateTime();
$this->phone = $phone;
$this->password = $password;
$this->roles = new ArrayCollection();
$this->cookie = $this->generateCookie();
}
/**
* @return DateTime
*/
public function getCreatedAt(): DateTime
{
return $this->createdAt;
}
/**
* @return string
*/
public function getPhone(): string
{
return $this->phone;
}
/**
* @return string
*/
public function getPassword(): string
{
return $this->password;
}
/**
* @return UserRole[]|Collection
*/
public function getRoles()
{
return $this->roles;
}
/**
* @return Cart|null
*/
public function getCart(): ?Cart
{
return $this->cart;
}
public function getManager(): ?Manager
{
return $this->manager;
}
public function setCookie(string $cookie): User
{
$this->cookie = $cookie;
return $this;
}
public function getCookie(): string
{
return $this->cookie;
}
public function renewCookie(): User
{
return $this->setCookie($this->generateCookie());
}
public function generateCookie(): string
{
return md5(time() . $this->getPhone() . $this->getPassword());
}
public function isInRoles(array $roles)
{
foreach ($this->getRoles() as $userRole) {
if(in_array($userRole->getRole(), $roles)) return true;
}
return false;
}
}