src/WebBundle/Service/RegistrationService.php line 89

Open in your IDE?
  1. <?php
  2. namespace WebBundle\Service;
  3. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  4. use Doctrine\ORM\EntityManager;
  5. use Doctrine\ORM\ORMException;
  6. use Exception;
  7. use FlexApp\Enum\LoggerJobNameEnum;
  8. use FlexApp\Events\Style43\RegistrationSuccessEvent;
  9. use FlexApp\Exceptions\PortalApiClientException;
  10. use FlexApp\Exceptions\UserIsNotValidException;
  11. use FlexApp\Service\Canonicalizer;
  12. use FlexApp\Service\LogsManager;
  13. use FlexApp\Service\UserPortalService;
  14. use Monolog\Logger;
  15. use Symfony\Component\DependencyInjection\ContainerInterface;
  16. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  17. use Symfony\Component\Form\FormFactory;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  20. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  21. use WebBundle\Entity\OrderAddress;
  22. use WebBundle\Entity\User;
  23. use WebBundle\Form\RegistrationFormType;
  24. use WebBundle\Form\UserRegistrationForm;
  25. use WebBundle\Helper\App;
  26. use WebBundle\Helper\Mailer;
  27. use WebBundle\Helper\PortalHelper;
  28. use WebBundle\Helper\UserHelper;
  29. class RegistrationService
  30. {
  31.     private $container;
  32.     private $portalService;
  33.     private $registrationForm;
  34.     private $user null;
  35.     private $logger;
  36.     private $em;
  37.     /**
  38.      * @var EventDispatcherInterface
  39.      */
  40.     private $eventDispatcher;
  41.     /** @required */
  42.     public UserPortalService $userPortalService;
  43.     /** @required */
  44.     public LocationService $locationService;
  45.     /** @required */
  46.     public Mailer $mailer;
  47.     /** @required */
  48.     public UserPasswordHasherInterface $userPasswordHasher;
  49.     /** @required */
  50.     public Canonicalizer $canonicalizer;
  51.     private LogsManager $logsManager;
  52.     public function __construct(
  53.         ContainerInterface $container,
  54.         PortalHelper $portalService,
  55.         Logger $logger,
  56.         EntityManager $em,
  57.         EventDispatcherInterface $eventDispatcher,
  58.         LogsManager $logsManager
  59.     ) {
  60.         $this->container $container;
  61.         $this->portalService $portalService;
  62.         $this->logger $logger;
  63.         $this->em $em;
  64.         $this->eventDispatcher $eventDispatcher;
  65.         $this->logsManager $logsManager;
  66.     }
  67.     /**
  68.      * Создает нового пользователя, возвращает true если создался и false в противном случае.
  69.      *
  70.      * @param Request $request
  71.      *
  72.      * @return User|null
  73.      *
  74.      * @throws ORMException
  75.      * @throws UniqueConstraintViolationException
  76.      * @throws Exception
  77.      */
  78.     public function register(Request $request): ?User
  79.     {
  80.         /** @var $formFactory FormFactory */
  81.         $formFactory $this->container->get('form.factory');
  82.         $userRegistrationForm = new UserRegistrationForm();
  83.         $this->registrationForm $formFactory->create(RegistrationFormType::class, $userRegistrationForm);
  84.         $this->registrationForm->setData($userRegistrationForm);
  85.         $this->registrationForm->handleRequest($request);
  86.         if (
  87.             !$this->registrationForm->isSubmitted()
  88.             || !$this->registrationForm->isValid()
  89.             || !$userRegistrationForm->getPlainPassword()
  90.             || !$userRegistrationForm->getEmail()
  91.         ) {
  92.             return null;
  93.         }
  94.         $token UserHelper::getInstance()->getToken();
  95.         $user = new User();
  96.         $user->setToken($token);
  97.         $user->setEnabled(true);
  98.         $user->setProved(false);
  99.         $user->setEmail($userRegistrationForm->getEmail());
  100.         $user->setUsername(null);
  101.         $user->setAlias(UserHelper::getUsernameEmail($userRegistrationForm->getEmail()));
  102.         $orderAddress = new OrderAddress();
  103.         $orderAddress->setIsMainRecipient(true);
  104.         $orderAddress->setToken($token);
  105.         $user->addOrderAddress($orderAddress);
  106.         if ('999' != $userRegistrationForm->getCountry()) {
  107.             $user->getMainRecipientAddress()->setCountry($this->em->getReference('WebBundle\Entity\ListCountry'$userRegistrationForm->getCountry()));
  108.         }
  109.         $user->getMainRecipientAddress()->setZipCode($userRegistrationForm->getZip());
  110.         $this->user $user;
  111.         $this->updateUser($user$userRegistrationForm->getPlainPassword());
  112.         $this->mailer->sendUserRegEmailMessage($user'********');
  113.         $this->sendUserToNewPortal($request$user);
  114.         return $this->user;
  115.     }
  116.     /**
  117.      * Автоматическое создание пользователя NEW used ONLY in TileExpert !!!
  118.      *
  119.      * @param       $email
  120.      * @param array $data
  121.      *
  122.      * @return User|null
  123.      *
  124.      * @throws Exception
  125.      */
  126.     public function autoRegisterNew($email$data = [])
  127.     {
  128.         $data['email'] = $email;
  129.         $oServiceUser App::getContainer()->get('app.service.user_profile');
  130.         try {
  131.             // обновляем данные юзера / или рега
  132.             $oUser $oServiceUser->saveUserByData($data);
  133.         } catch (UserIsNotValidException $exception) {
  134.             throw new BadRequestHttpException('User is not valid.');
  135.         }
  136.         if ($oServiceUser->hasErrors()) {
  137.             // тут желательно отдать ошибку
  138.             $error $oServiceUser->getErrors();
  139.             throw new BadRequestHttpException($error);
  140.         }
  141.         if (!$oUser) {
  142.             throw new Exception('Failed to get user');
  143.         }
  144.         if ('error' == $oUser->getUnid()) {
  145.             $attempts 5;
  146.             do {
  147.                 // если не первая попытка то делаем паузу
  148.                 if ($attempts 5) {
  149.                     sleep(2);
  150.                 }
  151.                 --$attempts;
  152.                 $unid $oServiceUser->getUserPortalUnid($oUser);
  153.             } while ($attempts && !$unid);
  154.             if (!$unid) {
  155.                 throw new Exception('Failed to get unid');
  156.             }
  157.         }
  158.         if (!('' === $oUser->getUnid() || 'error' === $oUser->getUnid() || null === $oUser->getUnid())) {
  159.             $this->eventDispatcher->dispatch(new RegistrationSuccessEvent($oUser));
  160.             $this->userPortalService->updateOrdersByUser($oUser);
  161.         }
  162.         return $oUser;
  163.     }
  164.     /**
  165.      * @return mixed
  166.      */
  167.     public function getUser()
  168.     {
  169.         return $this->user;
  170.     }
  171.     /**
  172.      * Возвращает форму для регистрации.
  173.      *
  174.      * @return mixed
  175.      */
  176.     public function getRegistrationForm()
  177.     {
  178.         return $this->registrationForm;
  179.     }
  180.     public function updateUser(User $user, ?string $password null)
  181.     {
  182.         if (null !== $password) {
  183.             $user->setPassword(
  184.                 $this->userPasswordHasher->hashPassword($user$password)
  185.             );
  186.         }
  187.         $emailCanonical $this->canonicalizer->canonicalize($user->getEmail());
  188.         $user->setEmail($emailCanonical);
  189.         if (!$this->em->contains($user)) {
  190.             $this->em->persist($user);
  191.         }
  192.         $this->em->flush();
  193.     }
  194.     /**
  195.      * Добавление пользователя на новый портал
  196.      */
  197.     private function sendUserToNewPortal(Request $requestUser $user): void
  198.     {
  199.         $record $this->locationService->getCityRecord($request->getClientIp());
  200.         $contact = [
  201.             'ContactStatus' => [7],
  202.             'FirstName' => "",
  203.             'ContactName' => "",
  204.             'EmailValues' => [$user->getEmail()],
  205.             'MainEmail' => $user->getEmail(),
  206.             'DocumentType' => 'Person',
  207.             'siteToken' => $user->getToken(),
  208.             'source' => 'RegistrationService::register',
  209.             'responsibleUnid' => 'B450D722-E901-27CF-DDCC-F6AF86BF5A5D',
  210.             'responsibleName' => 'Pavel Popov',
  211.             'Comment' => null !== $record ?
  212.                 implode(', 'array_filter([$record->country->name$record->city->name])) . ' (' $request->getClientIp() . ')' :
  213.                 $request->getClientIp(),
  214.         ];
  215.         try {
  216.             $result $this->portalService->createContactWithAdditionalFunctional($contact);
  217.             if (!empty($result) && !empty($result['contactUnid'])) {
  218.                 $user->setUnid($result['contactUnid']);
  219.                 $this->updateUser($user);
  220.                 $this->userPortalService->updateOrdersByUser($user);
  221.                 $this->user $user;
  222.                 $this->logger->info('CONTACT REG: ' print_r($contacttrue));
  223.                 $this->logger->info('CONTACT REG RESULT: ' print_r($contacttrue));
  224.                 $this->logsManager->logInfo(
  225.                     [
  226.                         'message' => [
  227.                             'CONTACT REG: ' print_r($contacttrue),
  228.                             'CONTACT REG RESULT: ' print_r($contacttrue),
  229.                         ],
  230.                     ],
  231.                     LoggerJobNameEnum::REGISTRATION_SERVICE_LOG
  232.                 );
  233.                 $this->eventDispatcher->dispatch(new RegistrationSuccessEvent($this->user));
  234.             }
  235.         } catch (PortalApiClientException $e) {
  236.             $this->logger->error('Отправка контакта на портал неуспешна: ' $e->getMessage());
  237.             $this->logsManager->logInfo(
  238.                 [
  239.                     'message' => 'Отправка контакта на портал неуспешна: ' $e->getMessage(),
  240.                 ],
  241.                 LoggerJobNameEnum::REGISTRATION_SERVICE_LOG
  242.             );
  243.         }
  244.     }
  245. }