Danyi Dávid 8f843a8194 * removed obsolete libs that are available as separate package
* updated fixtures
* updated fixture import soluzion
* updated jwt token handling parts
2018-11-17 21:39:13 +01:00

109 lines
2.6 KiB
PHP

<?php
namespace App\Service;
use App\Entity\User;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
use DoctrineExpressiveModule\Hydrator\DoctrineObject;
use Zend\Crypt\Password\Bcrypt;
class UserService
{
/**
* @var EntityManager
*/
private $em;
/**
* @var DoctrineObject
*/
private $hydrator;
public function __construct(EntityManager $em, DoctrineObject $hydrator)
{
$this->em = $em;
$this->hydrator = $hydrator;
}
/**
* Return FacilityLocations in a tree form
*
* @return array
*/
public function getList()
{
/** @var EntityRepository $treeRepository */
$repository = $this->em->getRepository(User::class);
return $repository->findAll();
}
/**
* @param int $id
* @return User
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
* @throws \Doctrine\ORM\TransactionRequiredException
*/
public function get(int $id): User
{
/** @var User $user */
$user = $this->em->find(User::class, $id);
return $user;
}
/**
* @param int $id
* @param $data
* @return User
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
* @throws \Doctrine\ORM\TransactionRequiredException
*/
public function update(int $id, $data): User
{
/** @var User $user */
$user = $this->hydrator->hydrate($data, $this->get($id));
$this->em->persist($user);
$this->em->flush();
return $user;
}
/**
* @param int $id
* @param string $old
* @param string $new
* @return User
* @throws \Exception
*/
public function changePassword(int $id, string $old, string $new): User
{
$user = $this->get($id);
$crypt = new Bcrypt();
$crypt->setCost(AuthService::PASSWORD_COST);
if (!$crypt->verify($old, $user->getPassword())) {
throw new \Exception("Old password doesn't match", 401);
}
$user->setPassword($crypt->create($new));
$this->em->flush();
return $user;
}
/**
* @param string $role
* @return User[]|null
*/
public function getAllUsersOfRole(string $role): ?array
{
$activeUsers = $this->em->getRepository(User::class)->findBy([
'active' => true,
]);
return array_filter($activeUsers, function (User $user) use ($role) {
return in_array($role, $user->getRoles());
});
}
}