<?php
namespace ARSHDF\UserBundle\Entity;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ObjectManager;
use Doctrine\Persistence\ObjectRepository;
class UserManager
{
private $class;
/**
* @var ObjectManager
*/
private $om;
public function __construct(EntityManagerInterface $om, $class)
{
$this->om = $om;
$this->class = $class;
}
public function createUser()
{
$class = $this->getClass();
return new $class();
}
public function completeUser($user){
$user->setEnabled(false);
$user->setDeleted(false);
$user->setToActivate(false);
$user->setCreatedAt(new \DateTime());
$user->setPassword("");
}
/**
* @return string
*/
public function getClass(): string
{
if (false !== strpos($this->class, ':')) {
$metadata = $this->om->getClassMetadata($this->class);
$this->class = $metadata->getName();
}
return $this->class;
}
public function deleteUser($user)
{
$this->om->remove($user);
$this->om->flush();
}
public function findUserById($id)
{
return $this->findUserBy(['id' => $id]);
}
public function findUserByEmail($email)
{
return $this->findUserBy(['email' => strtolower($email)]);
}
public function findUserByUsername($username)
{
return $this->findUserBy(['username' => strtolower($username)]);
}
public function findUserByUsernameOrEmail($usernameOrEmail)
{
if (preg_match('/^.+@\S+\.\S+$/', $usernameOrEmail)) {
$user = $this->findUserByEmail($usernameOrEmail);
if (null !== $user) {
return $user;
}
}
return $this->findUserByUsername($usernameOrEmail);
}
public function findUserBy(array $criteria)
{
return $this->getRepository()->findOneBy($criteria);
}
public function findUsersBy(array $criteria)
{
return $this->getRepository()->findBy($criteria);
}
public function findUsers()
{
return $this->getRepository()->findAll();
}
protected function getRepository(): ObjectRepository
{
return $this->om->getRepository($this->getClass());
}
public function getUserQueryBuilder(){
return $this->om->createQueryBuilder()
->select('u')
->from($this->class, 'u');
}
public function findOneByToken(string $token)
{
return $this->findUserBy(['token' => $token]);
}
public function findByRole(string $role){
$qb = $this->om->createQueryBuilder()
->select('u')
->from($this->class, 'u')
->andWhere('u.roles LIKE :roles')
->setParameter('roles', '%"'.$role.'"%')
->andWhere('u.enabled = 1')
;
return $qb->getQuery()->getResult();
}
}