src/Service/User/UserService.php line 124

Open in your IDE?
  1. <?php
  2. namespace App\Service\User;
  3. use App\Entity\User;
  4. use App\Entity\UserSettings;
  5. use App\Service\BaseEntityService;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Psr\Container\ContainerInterface;
  8. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  9. class UserService extends BaseEntityService
  10. {
  11.     /**
  12.      * @var ContainerInterface
  13.      */
  14.     private $container;
  15.     /**
  16.      * @var \App\Entity\User|null
  17.      */
  18.     private $currentReviewer;
  19.     /**
  20.      * @var UserPasswordHasherInterface
  21.      */
  22.     private $userPasswordHasher;
  23.     public function __construct(EntityManagerInterface      $emContainerInterface $container,
  24.                                 UserPasswordHasherInterface $userPasswordHasher)
  25.     {
  26.         parent::__construct($em);
  27.         $this->initialize(User::class);
  28.         $this->container $container;
  29.         $this->userPasswordHasher $userPasswordHasher;
  30.     }
  31.     public function getOrlovAvUser(): ?User
  32.     {
  33.         return $this->getFirst([
  34.             "firstName" => "Александр",
  35.             "lastName" => "Орлов",
  36.         ]);
  37.     }
  38.     public function getUchitelUser(): ?User
  39.     {
  40.         return $this->getFirst([
  41.             "firstName" => "Учитель",
  42.         ]);
  43.     }
  44.     /**
  45.      * Возвращает набор вариантов для поля User при редактировании TelegramDelayedMessage
  46.      * @param mixed $telegramDelayedMessage
  47.      * @return User[]
  48.      */
  49.     public function getTelegramDelayedMessageChoices($telegramDelayedMessage null): array
  50.     {
  51.         return $this->getBaseService()->getAll();
  52.     }
  53.     /**
  54.      * Возвращает текст метки для выбора User.
  55.      * Поддерживаем сигнатуру с 1 или 2 параметрами, чтобы AbstractBaseType мог вызывать любую из них.
  56.      */
  57.     public function getChoiceLabel(User $user$entity null): string
  58.     {
  59.         return $user->getFirstName() . ($user->getLastName() ? ' ' $user->getLastName() : '');
  60.     }
  61.     /**
  62.      * Возвращает всех кураторов
  63.      * @return User[]
  64.      */
  65.     public function getCurators(): array
  66.     {
  67.         /** @var User[] $users */
  68.         $users $this->getBaseService()->getAll();
  69.         $curators = [];
  70.         foreach ($users as $user) {
  71.             if ($user->getSettings()->isIsCurator()) {
  72.                 $curators[] = $user;
  73.             }
  74.         }
  75.         return $curators;
  76.     }
  77.     public function getReviewers(): array
  78.     {
  79.         /** @var User[] $users */
  80.         $users $this->getBaseService()->getAll();
  81.         $reviewers = [];
  82.         foreach ($users as $user) {
  83.             if ($user->getSettings()->isCanReviewCandidates()) {
  84.                 $reviewers[] = $user;
  85.             }
  86.         }
  87.         return $reviewers;
  88.     }
  89.     /**
  90.      * Возвращает варианты User для поля createdBy при редактировании Payment
  91.      * Вызывается динамически из AbstractBaseType::addEntityField при построении формы PaymentType
  92.      * @param mixed $payment
  93.      * @return User[]
  94.      */
  95.     public function getPaymentChoices($payment null): array
  96.     {
  97.         // По умолчанию возвращаем всех пользователей. При необходимости можно добавить фильтрацию.
  98.         return $this->getBaseService()->getAll();
  99.     }
  100.     /**
  101.      * Варианты пользователей для поля Candidate::curator.
  102.      * Вызывается динамически из AbstractBaseType::addEntityField как getCandidateChoices
  103.      * @param mixed $candidate
  104.      * @return User[]
  105.      */
  106.     public function getCandidateChoices($candidate null): array
  107.     {
  108.         // Используем список кураторов — это логичный набор для выбора кураторов кандидата.
  109.         return $this->getCurators();
  110.     }
  111.     public function getLoggedInUser(): ?User
  112.     {
  113.         if (!$this->container->has('security.token_storage')) {
  114.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  115.         }
  116.         if (null === $token $this->container->get('security.token_storage')->getToken()) {
  117.             return null;
  118.         }
  119.         // @deprecated since 5.4, $user will always be a UserInterface instance
  120.         if (!\is_object($user $token->getUser())) {
  121.             // e.g. anonymous authentication
  122.             return null;
  123.         }
  124.         return $user;
  125.     }
  126.     public function getLoggedInUserSettings(): ?UserSettings
  127.     {
  128.         $user $this->getLoggedInUser();
  129.         return $user $user->getSettings() : null;
  130.     }
  131.     public function getAvailableReviewer(): ?User
  132.     {
  133.         $user $this->getLoggedInUser();
  134.         if ($user && $user->getSettings()->isCanReviewCandidates()) {
  135.             return $user;
  136.         }
  137.         $reviewers $this->getReviewers();
  138.         return count($reviewers) > $reviewers[0] : null;
  139.     }
  140.     public function getCurrentReviewer(): ?\App\Entity\User
  141.     {
  142.         if (!$this->currentReviewer) {
  143.             $this->currentReviewer $this->getUchitelUser();
  144.         }
  145.         return $this->currentReviewer;
  146.     }
  147.     public function getStarCurator(): ?User
  148.     {
  149.         return $this->getFirst([
  150.             "firstName" => "*",
  151.         ]);
  152.     }
  153.     public function setUserPassword(User $userstring $password,
  154.         bool $flush true): bool
  155.     {
  156.         $oldHash $user->getPassword();
  157.         $isNewValid false;
  158.         try {
  159.             $isNewValid $oldHash && $this->userPasswordHasher->isPasswordValid($user$password);
  160.         } catch (\Throwable $e) {
  161.             //do nothing
  162.         }
  163.         if (!$isNewValid) {
  164.             $hash $this->userPasswordHasher->hashPassword($user$password);
  165.             $user->setPassword($hash);
  166.             if ($flush) {
  167.                 $this->em->persist($user);
  168.                 $this->em->flush();
  169.             }
  170.             return true;
  171.         }
  172.         return false;
  173.     }
  174. }