src/Controller/Website/Auth/RegisterController.php line 82

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Website\Auth;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use App\Controller\Website\Auth\AbstractController;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\Routing\Annotation\Route;
  8. use Sulu\Bundle\SecurityBundle\Entity\User;
  9. use Sulu\Component\Webspace\Manager\WebspaceManagerInterface;
  10. use App\Manager\UserManager;
  11. use Exception;
  12. use GuzzleHttp\Client;
  13. class RegisterController extends AbstractController
  14. {
  15.     protected $entityManager;
  16.     protected $webspaceManager;
  17.     protected $userManager;
  18.     protected $pathToCountriesCSV;
  19.     public function __construct(EntityManagerInterface $entityManagerWebspaceManagerInterface $webspaceManagerUserManager $userManager)
  20.     {
  21.         $this->entityManager $entityManager;
  22.         $this->webspaceManager $webspaceManager;
  23.         $this->userManager $userManager;
  24.     }
  25.     private function getCountriesFromCSV()
  26.     {
  27.         $data = [];
  28.         if (($handle fopen($this->pathToCountriesCSV'r')) !== false) {
  29.             while (($row fgetcsv($handle)) !== false) {
  30.                 $data[] = [
  31.                     'name' => $row[0],
  32.                     'id' => $row[1],
  33.                 ];
  34.             }
  35.             fclose($handle);
  36.         }
  37.         usort($data, function ($a$b) {
  38.             return strcoll($a['name'], $b['name']);
  39.         });
  40.         return $data;
  41.     }
  42.     public function findCountryById(string $id): ?string
  43.     {
  44.         if (($handle fopen($this->pathToCountriesCSV'r')) !== false) {
  45.             while (($row fgetcsv($handle)) !== false) {
  46.                 if ($row[1] === $id) {
  47.                     fclose($handle);
  48.                     return $row[0];
  49.                 }
  50.             }
  51.             fclose($handle);
  52.         }
  53.         return null;
  54.     }
  55.     /**
  56.      * @Route("/register", name="app_register_index", methods={"GET","HEAD"})
  57.      */
  58.     public function index(Request $request): Response
  59.     {
  60.         $this->pathToCountriesCSV $this->getParameter('kernel.project_dir') . '/src/Controller/Website/Auth/crm_countries.csv';
  61.         $error = match ($request->query->get('error')) {
  62.             'crm' => 'You have not passed validation through recaptcha.',
  63.             'user' => 'User not created. Please try again.',
  64.             default => null,
  65.         };
  66.         $capcha_site_key $_ENV['APP_ENV'] === 'dev' $_ENV['CAPTCHA_SITE_KEY_DEV'] : $_ENV['CAPTCHA_SITE_KEY_PROD'];
  67.         return $this->render('auth/register.html.twig', [
  68.             'countries' => $this->getCountriesFromCSV(),
  69.             'capcha_site_key' => $capcha_site_key,
  70.             'error' => $error,
  71.         ]);
  72.     }
  73.     //     /**
  74.     //      * @Route("/register-success", name="app_register_success_index", methods={"GET","HEAD"})
  75.     //      */
  76.     //     public function registerSuccessPage(Request $request): Response
  77.     //     {
  78.     //         $modernSiteUrl = $_ENV['APP_BASE_URL'];
  79.     //
  80.     //         return $this->render('auth/register-success.html.twig', [
  81.     //             'modernSiteUrl' => $modernSiteUrl,
  82.     //         ]);
  83.     //     }
  84.     /**
  85.      * @Route("/register", name="app_register_post", methods={"POST"})
  86.      */
  87.     public function register(Request $request): Response
  88.     {
  89.         $this->pathToCountriesCSV $this->getParameter('kernel.project_dir') . '/src/Controller/Website/Auth/crm_countries.csv';
  90.         $formData $request->request->all();
  91.         try {
  92.             $this->registerUserProccess($formData);
  93.         } catch (Exception $e) {
  94.             $this->redirect('/register?error=user');
  95.         }
  96.         try {
  97.             $this->sendToCrm($formData);
  98.         } catch (Exception $e) {
  99.             $this->redirect('/register?error=crm');
  100.         }
  101.         $modernSiteUrl $_ENV['APP_BASE_URL'];
  102.         return $this->render('auth/register-success.html.twig', [
  103.             'modernSiteUrl' => $modernSiteUrl,
  104.         ]);
  105.     }
  106.     private function registerUserProccess(array $formData)
  107.     {
  108.         $roleName 'website_user';
  109.         $webspaceKey 'modernexpo';
  110.         $user = new User();
  111.         $user $this->setUserPasswordAndSalt($user$formData);
  112.         if (null !== $formData['full_name']) {
  113.             $user->setUsername($formData['full_name']);
  114.         }
  115.         if (null !== $formData['email']) {
  116.             $user->setEmail($formData['email']);
  117.         }
  118.         $userLocale $user->getLocale();
  119.         if (null === $userLocale) {
  120.             $user->setLocale('en');
  121.         }
  122.         $user->setEnabled(true);
  123.         // Create User
  124.         $user $this->userManager->createUser($user$webspaceKey$roleName);
  125.     }
  126.     private function sendToCrm(array $formData): void
  127.     {
  128.         $url $_ENV['APP_ENV'] === 'dev' $_ENV['CRM_DEV_URL'] : $_ENV['CRM_PROD_URL'];
  129.         $recaptchaToken $formData['g-recaptcha-response'] ?? '';
  130.         if (!empty($formData['country_id']) && empty($formData['country_name'])) {
  131.             $formData['country_name'] = $this->findCountryById($formData['country_id']);
  132.         }
  133.         $body = [
  134.             'name' => 'Request Access to the media bank',
  135.             'mainForm' => [
  136.                 'id' => '827489bd-35b9-4e02-9770-131caf29b246',
  137.             ],
  138.             'submitForm' => [
  139.                 'id' => '827489bd-35b9-4e02-9770-131caf29b246',
  140.             ],
  141.             'formData' => [
  142.                 'full_name' => $formData['full_name'] ?? '',
  143.                 'company_name' => $formData['company_name'] ?? '',
  144.                 'email' => $formData['email'] ?? '',
  145.                 // 'password' => $formData['_password'] ?? '',
  146.                 'country' => [
  147.                     'id' => $formData['country_id'] ?? '728d079f-f712-4add-984c-e280cc0ae2d2',
  148.                     'name' => $formData['country_name'] ?? 'Ukraine',
  149.                 ],
  150.                 'phone' => $formData['phone'] ?? '',
  151.             ],
  152.         ];
  153.         $headers = [
  154.             'Content-Type' => 'application/json',
  155.             'X-Recaptcha-Token' => $recaptchaToken,
  156.         ];
  157.         try {
  158.             $client = new Client();
  159.             $response $client->post($url, [
  160.                 'headers' => $headers,
  161.                 'json' => $body,
  162.             ]);
  163.         } catch (\Throwable $e) {
  164.             $errorMessage sprintf('API request failed with message: %s, code: %d'$e->getMessage(), $e->getCode());
  165.             if ($_ENV['APP_ENV'] === 'dev') {
  166.                 dump('Request Body: '$body'Headers: '$headers);
  167.                 dump('Error: '$e);
  168.                 die();
  169.             }
  170.             error_log($errorMessage);
  171.             throw new \Exception($errorMessage$e->getCode(), $e);
  172.         }
  173.     }
  174. }