src/Service/User/UserService.php line 145

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 isLoggedInUser(?User $user): bool
  39.     {
  40.         if (!$user) {
  41.             return false;
  42.         }
  43.         $loggedInUser $this->getLoggedInUser();
  44.         return $loggedInUser && $loggedInUser->getId() === $user->getId();
  45.     }
  46.     public function isOrlovAV(): bool
  47.     {
  48.         $user $this->getOrlovAvUser();
  49.         return $this->isLoggedInUser($user);
  50.     }
  51.     public function getUchitelUser(): ?User
  52.     {
  53.         return $this->getFirst([
  54.             "firstName" => "Учитель",
  55.         ]);
  56.     }
  57.     /**
  58.      * Возвращает набор вариантов для поля User при редактировании TelegramDelayedMessage
  59.      * @param mixed $telegramDelayedMessage
  60.      * @return User[]
  61.      */
  62.     public function getTelegramDelayedMessageChoices($telegramDelayedMessage null): array
  63.     {
  64.         return $this->getBaseService()->getAll();
  65.     }
  66.     /**
  67.      * Возвращает текст метки для выбора User.
  68.      * Поддерживаем сигнатуру с 1 или 2 параметрами, чтобы AbstractBaseType мог вызывать любую из них.
  69.      */
  70.     public function getChoiceLabel(User $user$entity null): string
  71.     {
  72.         return $user->getFirstName() . ($user->getLastName() ? ' ' $user->getLastName() : '');
  73.     }
  74.     /**
  75.      * Возвращает всех кураторов
  76.      * @return User[]
  77.      */
  78.     public function getCurators(): array
  79.     {
  80.         /** @var User[] $users */
  81.         $users $this->getBaseService()->getAll();
  82.         $curators = [];
  83.         foreach ($users as $user) {
  84.             if ($user->getSettings()->isIsCurator()) {
  85.                 $curators[] = $user;
  86.             }
  87.         }
  88.         return $curators;
  89.     }
  90.     public function getReviewers(): array
  91.     {
  92.         /** @var User[] $users */
  93.         $users $this->getBaseService()->getAll();
  94.         $reviewers = [];
  95.         foreach ($users as $user) {
  96.             if ($user->getSettings()->isCanReviewCandidates()) {
  97.                 $reviewers[] = $user;
  98.             }
  99.         }
  100.         return $reviewers;
  101.     }
  102.     /**
  103.      * Возвращает варианты User для поля createdBy при редактировании Payment
  104.      * Вызывается динамически из AbstractBaseType::addEntityField при построении формы PaymentType
  105.      * @param mixed $payment
  106.      * @return User[]
  107.      */
  108.     public function getPaymentChoices($payment null): array
  109.     {
  110.         // По умолчанию возвращаем всех пользователей. При необходимости можно добавить фильтрацию.
  111.         return $this->getBaseService()->getAll();
  112.     }
  113.     /**
  114.      * Варианты пользователей для поля Candidate::curator.
  115.      * Вызывается динамически из AbstractBaseType::addEntityField как getCandidateChoices
  116.      * @param mixed $candidate
  117.      * @return User[]
  118.      */
  119.     public function getCandidateChoices($candidate null): array
  120.     {
  121.         // Используем список кураторов — это логичный набор для выбора кураторов кандидата.
  122.         return $this->getCurators();
  123.     }
  124.     public function getLoggedInUser(): ?User
  125.     {
  126.         if (!$this->container->has('security.token_storage')) {
  127.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  128.         }
  129.         if (null === $token $this->container->get('security.token_storage')->getToken()) {
  130.             return null;
  131.         }
  132.         // @deprecated since 5.4, $user will always be a UserInterface instance
  133.         if (!\is_object($user $token->getUser())) {
  134.             // e.g. anonymous authentication
  135.             return null;
  136.         }
  137.         return $user;
  138.     }
  139.     public function getLoggedInUserSettings(): ?UserSettings
  140.     {
  141.         $user $this->getLoggedInUser();
  142.         return $user $user->getSettings() : null;
  143.     }
  144.     public function getAvailableReviewer(): ?User
  145.     {
  146.         $user $this->getLoggedInUser();
  147.         if ($user && $user->getSettings()->isCanReviewCandidates()) {
  148.             return $user;
  149.         }
  150.         $reviewers $this->getReviewers();
  151.         return count($reviewers) > $reviewers[0] : null;
  152.     }
  153.     public function getCurrentReviewer(): ?\App\Entity\User
  154.     {
  155.         if (!$this->currentReviewer) {
  156.             $this->currentReviewer $this->getUchitelUser();
  157.         }
  158.         return $this->currentReviewer;
  159.     }
  160.     public function getStarCurator(): ?User
  161.     {
  162.         return $this->getFirst([
  163.             "firstName" => "*",
  164.         ]);
  165.     }
  166.     public function setUserPassword(User $userstring $password,
  167.         bool $flush true): bool
  168.     {
  169.         $oldHash $user->getPassword();
  170.         $isNewValid false;
  171.         try {
  172.             $isNewValid $oldHash && $this->userPasswordHasher->isPasswordValid($user$password);
  173.         } catch (\Throwable $e) {
  174.             //do nothing
  175.         }
  176.         if (!$isNewValid) {
  177.             $hash $this->userPasswordHasher->hashPassword($user$password);
  178.             $user->setPassword($hash);
  179.             if ($flush) {
  180.                 $this->em->persist($user);
  181.                 $this->em->flush();
  182.             }
  183.             return true;
  184.         }
  185.         return false;
  186.     }
  187. }