src/Service/User/UserService.php line 128

Open in your IDE?
  1. <?php
  2. namespace App\Service\User;
  3. use App\Core\Persistence\BaseEntityService;
  4. use App\Entity\User;
  5. use App\Entity\UserSettings;
  6. use App\Service\AccessToken\AccessTokenService;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Psr\Container\ContainerInterface;
  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.     private AccessTokenService $accessTokenService;
  20.     public function __construct(EntityManagerInterface $em,
  21.                                 ContainerInterface $container,
  22.                                 AccessTokenService $accessTokenService)
  23.     {
  24.         parent::__construct($em);
  25.         $this->initialize(User::class);
  26.         $this->container $container;
  27.         $this->accessTokenService $accessTokenService;
  28.     }
  29.     public function getOrlovAvUser(): ?User
  30.     {
  31.         return $this->getBaseService()->getFirst([
  32.             "firstName" => "Александр",
  33.             "lastName" => "Орлов",
  34.         ]);
  35.     }
  36.     public function getUchitelUser(): ?User
  37.     {
  38.         return $this->getBaseService()->getFirst([
  39.             "firstName" => "Учитель",
  40.         ]);
  41.     }
  42.     /**
  43.      * Возвращает набор вариантов для поля User при редактировании TelegramDelayedMessage
  44.      * @param mixed $telegramDelayedMessage
  45.      * @return User[]
  46.      */
  47.     public function getTelegramDelayedMessageChoices($telegramDelayedMessage null): array
  48.     {
  49.         return $this->getBaseService()->getAll();
  50.     }
  51.     /**
  52.      * Возвращает текст метки для выбора User.
  53.      * Поддерживаем сигнатуру с 1 или 2 параметрами, чтобы AbstractBaseType мог вызывать любую из них.
  54.      */
  55.     public function getChoiceLabel(User $user$entity null): string
  56.     {
  57.         return $user->getFirstName() . ($user->getLastName() ? ' ' $user->getLastName() : '');
  58.     }
  59.     /**
  60.      * Возвращает всех кураторов
  61.      * @return User[]
  62.      */
  63.     public function getCurators(): array
  64.     {
  65.         /** @var User[] $users */
  66.         $users $this->getBaseService()->getAll();
  67.         $curators = [];
  68.         foreach ($users as $user) {
  69.             if ($user->getSettings()->isIsCurator()) {
  70.                 $curators[] = $user;
  71.             }
  72.         }
  73.         return $curators;
  74.     }
  75.     public function getReviewers(): array
  76.     {
  77.         /** @var User[] $users */
  78.         $users $this->getBaseService()->getAll();
  79.         $reviewers = [];
  80.         foreach ($users as $user) {
  81.             if ($user->getSettings()->isCanReviewCandidates()) {
  82.                 $reviewers[] = $user;
  83.             }
  84.         }
  85.         return $reviewers;
  86.     }
  87.     /**
  88.      * Возвращает варианты User для поля createdBy при редактировании Payment
  89.      * Вызывается динамически из AbstractBaseType::addEntityField при построении формы PaymentType
  90.      * @param mixed $payment
  91.      * @return User[]
  92.      */
  93.     public function getPaymentChoices($payment null): array
  94.     {
  95.         // По умолчанию возвращаем всех пользователей. При необходимости можно добавить фильтрацию.
  96.         return $this->getBaseService()->getAll();
  97.     }
  98.     /**
  99.      * Варианты пользователей для поля Candidate::curator.
  100.      * Вызывается динамически из AbstractBaseType::addEntityField как getCandidateChoices
  101.      * @param mixed $candidate
  102.      * @return User[]
  103.      */
  104.     public function getCandidateChoices($candidate null): array
  105.     {
  106.         // Используем список кураторов — это логичный набор для выбора кураторов кандидата.
  107.         return $this->getCurators();
  108.     }
  109.     public function getLoggedInUser(): ?User
  110.     {
  111.         if (!$this->container->has('security.token_storage')) {
  112.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  113.         }
  114.         $token $this->container->get('security.token_storage')->getToken();
  115.         // @deprecated since 5.4, $user will always be a UserInterface instance
  116.         if (!$token || !\is_object($user $token->getUser())) {
  117.             // e.g. anonymous authentication
  118.             $user $this->getLoggedInUserByCookiesAccessToken();
  119.         }
  120.         return $user;
  121.     }
  122.     public function getLoggedInUserSettings(): ?UserSettings
  123.     {
  124.         $user $this->getLoggedInUser();
  125.         return $user $user->getSettings() : null;
  126.     }
  127.     public function getAvailableReviewer(): ?User
  128.     {
  129.         $user $this->getLoggedInUser();
  130.         if ($user && $user->getSettings()->isCanReviewCandidates()) {
  131.             return $user;
  132.         }
  133.         $reviewers $this->getReviewers();
  134.         return count($reviewers) > $reviewers[0] : null;
  135.     }
  136.     public function getCurrentReviewer(): ?\App\Entity\User
  137.     {
  138.         if (!$this->currentReviewer) {
  139.             $this->currentReviewer $this->getUchitelUser();
  140.         }
  141.         return $this->currentReviewer;
  142.     }
  143.     public function getStarCurator(): ?User
  144.     {
  145.         return $this->getBaseService()->getFirst([
  146.             "firstName" => "*",
  147.         ]);
  148.     }
  149.     /**
  150.      * @param string $string
  151.      * @return array|User[]
  152.      */
  153.     public function findUsersByPhone(string $string): array
  154.     {
  155.         if (strpos($string"8") === 0) {
  156.             $string substr($string1);
  157.         }
  158.         $string2 "%" $string "%";
  159.         $stringArr preg_split("/[\s]+/"$string);
  160.         $stringArr array_map(function ($item) {
  161.             return "%" trim($item) . "%";
  162.         }, $stringArr);
  163.         $fieldsArr = ["firstName""lastName"'patronymic'];
  164.         $requestPart2 "";
  165.         foreach ($fieldsArr as $field) {
  166.             foreach ($stringArr as $item) {
  167.                 $requestPart2 .= ($requestPart2 " or" "" ) . " item.$field like '$item'";
  168.             }
  169.         }
  170.         $requestPart2 =" ($requestPart2)";
  171.         $stringRequests $requestPart2 " or ($requestPart2)" "";
  172.         $q $this->em->getRepository(User::class)->createQueryBuilder('item');
  173.         $q
  174.             ->andWhere("item.phone = '$string' or item.phone = '+$string'"
  175.                 " or item.phone = '+7$string' or item.phone = '8$string' or item.lastName like :string2 or item.firstName like :string2"
  176.                 $stringRequests
  177.             )
  178.             ->setParameter('string2'$string2);
  179.         ;
  180.         $result $q->getQuery()->getResult();
  181.         return $result;
  182.     }
  183.     public function toArray(User $user): array
  184.     {
  185.         $userData $user->toArray();
  186.         $keysFilter = ["id""username"'firstName''lastName''patronymic''phone'];
  187.         foreach ($userData as $key => $value) {
  188.             if (!in_array($key$keysFilter)) {
  189.                 unset($userData[$key]);
  190.             }
  191.         }
  192.         $userData["name"] = $user->getName();
  193.         return $userData;
  194.     }
  195.     public function getLoggedInUserByCookiesAccessToken(): ?User
  196.     {
  197.         $token $this->accessTokenService->getByCookies();
  198.         if ($token) {
  199.             return $token->getUser();
  200.         }
  201.         return null;
  202.     }
  203. }