src/WebBundle/Service/RegistrationService.php line 79

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