<?php
namespace App\Service\User;
use App\Entity\User;
use App\Entity\UserSettings;
use App\Service\BaseEntityService;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Container\ContainerInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class UserService extends BaseEntityService
{
/**
* @var ContainerInterface
*/
private $container;
/**
* @var \App\Entity\User|null
*/
private $currentReviewer;
/**
* @var UserPasswordHasherInterface
*/
private $userPasswordHasher;
public function __construct(EntityManagerInterface $em, ContainerInterface $container,
UserPasswordHasherInterface $userPasswordHasher)
{
parent::__construct($em);
$this->initialize(User::class);
$this->container = $container;
$this->userPasswordHasher = $userPasswordHasher;
}
public function getOrlovAvUser(): ?User
{
return $this->getFirst([
"firstName" => "Александр",
"lastName" => "Орлов",
]);
}
public function getUchitelUser(): ?User
{
return $this->getFirst([
"firstName" => "Учитель",
]);
}
/**
* Возвращает набор вариантов для поля User при редактировании TelegramDelayedMessage
* @param mixed $telegramDelayedMessage
* @return User[]
*/
public function getTelegramDelayedMessageChoices($telegramDelayedMessage = null): array
{
return $this->getBaseService()->getAll();
}
/**
* Возвращает текст метки для выбора User.
* Поддерживаем сигнатуру с 1 или 2 параметрами, чтобы AbstractBaseType мог вызывать любую из них.
*/
public function getChoiceLabel(User $user, $entity = null): string
{
return $user->getFirstName() . ($user->getLastName() ? ' ' . $user->getLastName() : '');
}
/**
* Возвращает всех кураторов
* @return User[]
*/
public function getCurators(): array
{
/** @var User[] $users */
$users = $this->getBaseService()->getAll();
$curators = [];
foreach ($users as $user) {
if ($user->getSettings()->isIsCurator()) {
$curators[] = $user;
}
}
return $curators;
}
public function getReviewers(): array
{
/** @var User[] $users */
$users = $this->getBaseService()->getAll();
$reviewers = [];
foreach ($users as $user) {
if ($user->getSettings()->isCanReviewCandidates()) {
$reviewers[] = $user;
}
}
return $reviewers;
}
/**
* Возвращает варианты User для поля createdBy при редактировании Payment
* Вызывается динамически из AbstractBaseType::addEntityField при построении формы PaymentType
* @param mixed $payment
* @return User[]
*/
public function getPaymentChoices($payment = null): array
{
// По умолчанию возвращаем всех пользователей. При необходимости можно добавить фильтрацию.
return $this->getBaseService()->getAll();
}
/**
* Варианты пользователей для поля Candidate::curator.
* Вызывается динамически из AbstractBaseType::addEntityField как getCandidateChoices
* @param mixed $candidate
* @return User[]
*/
public function getCandidateChoices($candidate = null): array
{
// Используем список кураторов — это логичный набор для выбора кураторов кандидата.
return $this->getCurators();
}
public function getLoggedInUser(): ?User
{
if (!$this->container->has('security.token_storage')) {
throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
}
if (null === $token = $this->container->get('security.token_storage')->getToken()) {
return null;
}
// @deprecated since 5.4, $user will always be a UserInterface instance
if (!\is_object($user = $token->getUser())) {
// e.g. anonymous authentication
return null;
}
return $user;
}
public function getLoggedInUserSettings(): ?UserSettings
{
$user = $this->getLoggedInUser();
return $user ? $user->getSettings() : null;
}
public function getAvailableReviewer(): ?User
{
$user = $this->getLoggedInUser();
if ($user && $user->getSettings()->isCanReviewCandidates()) {
return $user;
}
$reviewers = $this->getReviewers();
return count($reviewers) > 0 ? $reviewers[0] : null;
}
public function getCurrentReviewer(): ?\App\Entity\User
{
if (!$this->currentReviewer) {
$this->currentReviewer = $this->getUchitelUser();
}
return $this->currentReviewer;
}
public function getStarCurator(): ?User
{
return $this->getFirst([
"firstName" => "*",
]);
}
public function setUserPassword(User $user, string $password,
bool $flush = true): bool
{
$oldHash = $user->getPassword();
$isNewValid = false;
try {
$isNewValid = $oldHash && $this->userPasswordHasher->isPasswordValid($user, $password);
} catch (\Throwable $e) {
//do nothing
}
if (!$isNewValid) {
$hash = $this->userPasswordHasher->hashPassword($user, $password);
$user->setPassword($hash);
if ($flush) {
$this->em->persist($user);
$this->em->flush();
}
return true;
}
return false;
}
}