* initial commit
This commit is contained in:
102
src/App/Service/UserService.php
Normal file
102
src/App/Service/UserService.php
Normal file
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Entity\User;
|
||||
use App\Hydrator\DoctrineObject;
|
||||
use Doctrine\ORM\EntityManager;
|
||||
use Doctrine\ORM\EntityRepository;
|
||||
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
|
||||
*/
|
||||
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
|
||||
*/
|
||||
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());
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user