src/Controller/Shop/CustomerController.php line 130

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Shop;
  3. use App\Security\Guard\ShopUserProxyAuthenticator;
  4. use App\Service\ApiBridge;
  5. use Psr\Container\ContainerExceptionInterface;
  6. use Psr\Container\NotFoundExceptionInterface;
  7. use Sylius\Bundle\ResourceBundle\Controller\ResourceController;
  8. use Sylius\Component\Resource\Exception\UpdateHandlingException;
  9. use Sylius\Component\Resource\ResourceActions;
  10. use Symfony\Component\Form\Extension\Core\Type\TextType;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\HttpKernel\Exception\HttpException;
  14. use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
  15. use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
  16. use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
  17. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  18. class CustomerController extends ResourceController
  19. {
  20.     public const REGISTRATION_TYPE_INDIVIDUAL 'individual';
  21.     public const REGISTRATION_TYPE_ESTABLISHMENT 'establishment';
  22.     /**
  23.      * Override Shop registration form
  24.      *
  25.      * @param Request $request
  26.      * @return Response
  27.      * @throws \JsonException
  28.      * @throws ContainerExceptionInterface
  29.      * @throws NotFoundExceptionInterface
  30.      * @throws ClientExceptionInterface
  31.      * @throws RedirectionExceptionInterface
  32.      * @throws ServerExceptionInterface
  33.      * @throws TransportExceptionInterface
  34.      */
  35.     public function createAction(Request $request): Response
  36.     {
  37.         // Get registration type
  38.         $registrationType $request->query->get('t');
  39.         // Create config
  40.         $configuration $this->requestConfigurationFactory->create($this->metadata$request);
  41.         // Check isGranted
  42.         $this->isGrantedOr403($configurationResourceActions::CREATE);
  43.         // Create resource by config
  44.         $newResource $this->newResourceFactory->create($configuration$this->factory);
  45.         // Create form from config & resource
  46.         $form $this->resourceFormFactory->create($configuration$newResource);
  47.         $form->add('id'TextType::class);
  48.         $form->handleRequest($request);
  49.         // POST form
  50.         if ($request->isMethod(Request::METHOD_POST) && $form->isSubmitted() && $form->isValid()) {
  51.             $apiBridge $this->container->get('app.api_bridge');
  52.             // Create User in CRM
  53.             /// Handle CRM StructureContact creation
  54.             if ($registrationType === self::REGISTRATION_TYPE_INDIVIDUAL) {
  55.                 $this->handleContactCreation($apiBridge$form);
  56.             }
  57.             /// Handle CRM StructureEstablishment && StructureContact creation
  58.             if ($registrationType === self::REGISTRATION_TYPE_ESTABLISHMENT) {
  59.                 $this->handleEstablishmentAndContactCreation($apiBridge$form);
  60.             }
  61.             $newResource $form->getData();
  62.             // Add VEL_OTHER role to newly created ShopUser
  63.             $newResource->getUser()->addRole(ShopUserProxyAuthenticator::ROLE_VEL_OTHER);
  64.             // Force add Newsletter
  65.             $newResource->setSubscribedToNewsletter($form->get('newsletterFntvServices')->getData());
  66.             $event $this->eventDispatcher->dispatchPreEvent(ResourceActions::CREATE$configuration$newResource);
  67.             if ($event->isStopped() && !$configuration->isHtmlRequest()) {
  68.                 throw new HttpException($event->getErrorCode(), $event->getMessage());
  69.             }
  70.             if ($event->isStopped()) {
  71.                 $this->flashHelper->addFlashFromEvent($configuration$event);
  72.                 $eventResponse $event->getResponse();
  73.                 return $eventResponse ?? $this->redirectHandler->redirectToIndex($configuration$newResource);
  74.             }
  75.             if ($configuration->hasStateMachine()) {
  76.                 $stateMachine $this->getStateMachine();
  77.                 $stateMachine->apply($configuration$newResource);
  78.             }
  79.             $this->repository->add($newResource);
  80.             if ($configuration->isHtmlRequest()) {
  81.                 $this->flashHelper->addSuccessFlash($configurationResourceActions::CREATE$newResource);
  82.             }
  83.             $postEvent $this->eventDispatcher->dispatchPostEvent(ResourceActions::CREATE$configuration$newResource);
  84.             if (!$configuration->isHtmlRequest()) {
  85.                 return $this->createRestView($configuration$newResourceResponse::HTTP_CREATED);
  86.             }
  87.             $postEventResponse $postEvent->getResponse();
  88.             return $postEventResponse ?? $this->redirectHandler->redirectToResource($configuration$newResource);
  89.         }
  90.         if (!$configuration->isHtmlRequest()) {
  91.             return $this->createRestView($configuration$formResponse::HTTP_BAD_REQUEST);
  92.         }
  93.         $initializeEvent $this->eventDispatcher->dispatchInitializeEvent(ResourceActions::CREATE$configuration$newResource);
  94.         $initializeEventResponse $initializeEvent->getResponse();
  95.         return $initializeEventResponse ?? $this->render($configuration->getTemplate(ResourceActions::CREATE '.html'), [
  96.                 'configuration' => $configuration,
  97.                 'metadata' => $this->metadata,
  98.                 'resource' => $newResource,
  99.                 $this->metadata->getName() => $newResource,
  100.                 'form' => $form->createView()
  101.             ]);
  102.     }
  103.     /**
  104.      * @param ApiBridge $apiBridge
  105.      * @param $newResource
  106.      * @return void
  107.      * @throws ClientExceptionInterface
  108.      * @throws RedirectionExceptionInterface
  109.      * @throws ServerExceptionInterface
  110.      * @throws TransportExceptionInterface
  111.      * @throws \JsonException
  112.      */
  113.     private function handleEstablishmentAndContactCreation(ApiBridge $apiBridge$form): void
  114.     {
  115.         // Create Establishment
  116.         $establishment $apiBridge->createEstablishment([
  117.             'structureName' => $form->get('structureName')->getData(),
  118.             'activity' => $form->get('activity')->getData(),
  119.             'address' => $form->get('address')->getData(),
  120.             'zipCode' => $form->get('zipCode')->getData(),
  121.             'city' => $form->get('city')->getData(),
  122.             'country' => $form->get('country')->getData(),
  123.             'structurePhoneNumber' => $form->get('structurePhoneNumber')->getData(),
  124.             'structureSubType' => 'Client'
  125.         ]);
  126.         $establishment json_decode($establishment->getContent(), true512JSON_THROW_ON_ERROR)['data'];
  127.         $establishmentId $establishment['data']['establishment_id'];
  128.         // Create Contact
  129.         // If Structure Contact doesn't already exist in CRM
  130.         if (false === $apiBridge->structureContactExists($form->get('email')->getData())) {
  131.             $apiBridge->createStructureContact([
  132.                 'email' => $form->get('email')->getData(),
  133.                 'firstname' => $form->get('firstName')->getData(),
  134.                 'lastname' => $form->get('lastName')->getData(),
  135.                 'phone' => $form->get('phoneNumber')->getData(),
  136.                 'newsletterFntvServices' => $form->get('newsletterFntvServices')->getData(),
  137.                 'subProfession' => 'GĂ©rant'
  138.             ], $establishmentId);
  139.         }
  140.     }
  141.     /**
  142.      * @param ApiBridge $apiBridge
  143.      * @param $form
  144.      * @return void
  145.      * @throws ClientExceptionInterface
  146.      * @throws RedirectionExceptionInterface
  147.      * @throws ServerExceptionInterface
  148.      * @throws TransportExceptionInterface
  149.      * @throws \JsonException
  150.      */
  151.     private function handleContactCreation(ApiBridge $apiBridge$form): void
  152.     {
  153.         // If Structure Contact doesn't already exist in CRM
  154.         if (false === $apiBridge->structureContactExists($form->get('email')->getData())) {
  155.             $apiBridge->createStructureContact([
  156.                 'email' => $form->get('email')->getData(),
  157.                 'firstname' => $form->get('firstName')->getData(),
  158.                 'lastname' => $form->get('lastName')->getData(),
  159.                 'phone' => $form->get('phoneNumber')->getData(),
  160.                 'newsletterFntvServices' => $form->get('newsletterFntvServices')->getData(),
  161.                 'subProfession' => $this->getParameter('default_vel_sub_profession_id'),
  162.             ], $this->getParameter('default_vel_structure_id'));
  163.         }
  164.     }
  165.     /**
  166.      * Override Shop edit account form
  167.      *
  168.      * @param Request $request
  169.      * @return Response
  170.      * @throws ClientExceptionInterface
  171.      * @throws ContainerExceptionInterface
  172.      * @throws NotFoundExceptionInterface
  173.      * @throws RedirectionExceptionInterface
  174.      * @throws ServerExceptionInterface
  175.      * @throws TransportExceptionInterface
  176.      * @throws \JsonException
  177.      */
  178.     public function updateAction(Request $request): Response
  179.     {
  180.         $configuration $this->requestConfigurationFactory->create($this->metadata$request);
  181.         $this->isGrantedOr403($configurationResourceActions::UPDATE);
  182.         $resource $this->findOr404($configuration);
  183.         $form $this->resourceFormFactory->create($configuration$resource);
  184.         $form->handleRequest($request);
  185.         if (
  186.             \in_array($request->getMethod(), ['POST''PUT''PATCH'], true)
  187.             && $form->isSubmitted()
  188.             && $form->isValid()
  189.         ) {
  190.             $resource $form->getData();
  191.             $event $this->eventDispatcher->dispatchPreEvent(ResourceActions::UPDATE$configuration$resource);
  192.             if ($event->isStopped() && !$configuration->isHtmlRequest()) {
  193.                 throw new HttpException($event->getErrorCode(), $event->getMessage());
  194.             }
  195.             if ($event->isStopped()) {
  196.                 $this->flashHelper->addFlashFromEvent($configuration$event);
  197.                 $eventResponse $event->getResponse();
  198.                 return $eventResponse ?? $this->redirectHandler->redirectToResource($configuration$resource);
  199.             }
  200.             try {
  201.                 $this->resourceUpdateHandler->handle($resource$configuration$this->manager);
  202.                 // Update User in CRM
  203.                 /** @var ApiBridge $apiBridge */
  204.                 $apiBridge $this->container->get('app.api_bridge');
  205.                 if (true === $apiBridge->structureContactExists($resource->getEmail())) {
  206.                     $apiBridge->updateStructureContact([
  207.                         'email' => $resource->getEmail(),
  208.                         'firstname' => $resource->getFirstName(),
  209.                         'lastname' => $resource->getLastName(),
  210.                         'phone' => $resource->getPhoneNumber(),
  211.                         'birthday' => $resource->getBirthday(),
  212.                         'newsletterFntvServices' => $resource->isSubscribedToNewsletter()
  213.                     ]);
  214.                 }
  215.             } catch (UpdateHandlingException $exception) {
  216.                 if (!$configuration->isHtmlRequest()) {
  217.                     return $this->createRestView($configuration$form$exception->getApiResponseCode());
  218.                 }
  219.                 $this->flashHelper->addErrorFlash($configuration$exception->getFlash());
  220.                 return $this->redirectHandler->redirectToReferer($configuration);
  221.             }
  222.             if ($configuration->isHtmlRequest()) {
  223.                 $this->flashHelper->addSuccessFlash($configurationResourceActions::UPDATE$resource);
  224.             }
  225.             $postEvent $this->eventDispatcher->dispatchPostEvent(ResourceActions::UPDATE$configuration$resource);
  226.             if (!$configuration->isHtmlRequest()) {
  227.                 if ($configuration->getParameters()->get('return_content'false)) {
  228.                     return $this->createRestView($configuration$resourceResponse::HTTP_OK);
  229.                 }
  230.                 return $this->createRestView($configurationnullResponse::HTTP_NO_CONTENT);
  231.             }
  232.             $postEventResponse $postEvent->getResponse();
  233.             return $postEventResponse ?? $this->redirectHandler->redirectToResource($configuration$resource);
  234.         }
  235.         if (!$configuration->isHtmlRequest()) {
  236.             return $this->createRestView($configuration$formResponse::HTTP_BAD_REQUEST);
  237.         }
  238.         $initializeEvent $this->eventDispatcher->dispatchInitializeEvent(ResourceActions::UPDATE$configuration$resource);
  239.         $initializeEventResponse $initializeEvent->getResponse();
  240.         return $initializeEventResponse ?? $this->render($configuration->getTemplate(ResourceActions::UPDATE '.html'), [
  241.                 'configuration' => $configuration,
  242.                 'metadata' => $this->metadata,
  243.                 'resource' => $resource,
  244.                 $this->metadata->getName() => $resource,
  245.                 'form' => $form->createView()
  246.             ]);
  247.     }
  248. }