src/Event/EasyAdminSubscriber.php line 363

Open in your IDE?
  1. <?php
  2. namespace App\Event;
  3. use App\Entity\BookingRoom;
  4. use App\Entity\BuildingOption;
  5. use App\Entity\Company;
  6. use App\Entity\Country;
  7. use App\Entity\Logs;
  8. use App\Entity\NotificationPush;
  9. use App\Entity\Payment;
  10. use App\Entity\Room;
  11. use App\Entity\RoomOption;
  12. use App\Entity\Town;
  13. use App\Entity\User;
  14. use App\Security\EmailVerifier;
  15. use App\Service\Notification;
  16. use Doctrine\ORM\EntityManagerInterface;
  17. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterCrudActionEvent;
  18. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityBuiltEvent;
  19. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
  20. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
  21. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  22. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  23. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityDeletedEvent;
  24. use Exception;
  25. use GuzzleHttp\Exception\RequestException;
  26. use Psr\Log\LoggerInterface;
  27. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  28. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  29. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  30. use Symfony\Component\HttpFoundation\RequestStack;
  31. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  32. use Symfony\Component\HttpKernel\KernelInterface;
  33. use Symfony\Component\HttpKernel\Log\Logger;
  34. use Symfony\Component\Mime\Address;
  35. use Symfony\Component\Notifier\Bridge\Firebase\FirebaseTransport;
  36. use Symfony\Component\Notifier\Bridge\Firebase\Notification\AndroidNotification;
  37. use Symfony\Component\Notifier\Chatter;
  38. use Symfony\Component\Notifier\ChatterInterface;
  39. use Symfony\Component\Notifier\Event\MessageEvent;
  40. use Symfony\Component\Notifier\Message\ChatMessage;
  41. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  42. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  43. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  44. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  45. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  46. use Symfony\Component\Translation\TranslatableMessage;
  47. use Symfony\Contracts\Translation\TranslatorInterface;
  48. class EasyAdminSubscriber implements EventSubscriberInterface
  49. {
  50.     private $environment;
  51.     const RESEND_MAIL "app_resend_email";
  52.     const GENERATE_PAYMENT "app_payment";
  53.     const NOTIFY_PAYMENT "app_payment_notify";
  54.     private $emailVerifier;
  55.     private $token;
  56.     private $requestStack;
  57.     private $tokenStorage;
  58.     private $eventDispatcher;
  59.     private $session;
  60.     private $entityManager;
  61.     private $chatter;
  62.     private $logger;
  63.     private $encoder;
  64.     private $urlGenerator;
  65.     public function __construct(EmailVerifier $emailVerifier,
  66.                                 UserPasswordHasherInterface $encoder,
  67.                                 EventDispatcherInterface $eventDispatcher,
  68.                                 TokenStorageInterface $tokenStorage,
  69.                                 SessionInterface $session,
  70.                                 ChatterInterface $chatter,
  71.                                 LoggerInterface $logger,
  72.                                 KernelInterface $kernel,
  73.                                 UrlGeneratorInterface $urlGenerator,
  74.                                 EntityManagerInterface $entityManager,
  75.                                 RequestStack $requestStack)
  76.     {
  77.         $this->emailVerifier $emailVerifier;
  78.         $this->session $session;
  79.         $this->chatter $chatter;
  80.         $this->logger $logger;
  81.         $this->encoder $encoder;
  82.         $this->urlGenerator $urlGenerator;
  83.         $this->environment $kernel->getEnvironment();
  84.         $this->requestStack=$requestStack;
  85.         $this->entityManager=$entityManager;
  86.         $this->tokenStorage $tokenStorage;
  87.         $this->eventDispatcher $eventDispatcher;
  88.     }
  89.     public static function getSubscribedEvents()
  90.     {
  91.         return [
  92.             BeforeCrudActionEvent::class => ['setUserApp'],
  93.             AfterEntityBuiltEvent::class => ['onAfterBuiltEntity'],
  94.             AfterCrudActionEvent::class => ['afterCrudLaunch'],
  95.             AfterEntityPersistedEvent::class => ['onCreateEntity'],
  96.             BeforeEntityUpdatedEvent::class => ['onUpdateEntity'],
  97.             BeforeEntityDeletedEvent::class => ['onDeleteEntity'],
  98.             BeforeEntityPersistedEvent::class => ['onBeforeCreateEntity'],
  99.         ];
  100.     }
  101.     public function afterCrudLaunch(AfterCrudActionEvent $event){
  102.     }
  103.     public function setUserApp(BeforeCrudActionEvent $event)
  104.     {
  105.         $context $event->getAdminContext();
  106.     }
  107.     public function onCreateEntity(AfterEntityPersistedEvent $event){
  108.         $error=false;
  109.         $entity $event->getEntityInstance();
  110.         if($entity instanceof BookingRoom) {
  111.             if ($entity->getPayment()->getAmount() != $entity->getRoom()->getCost()) {
  112.                 $this->session->getFlashBag()->add("warning""Payment amount did'nt match with the room cost");
  113.                 $error true;
  114.             }
  115.             if ($entity->getArrivalDate() > $entity->getDepartureDate()) {
  116.                 $this->session->getFlashBag()->add("warning""Invalid departure date " $entity->getDepartureDate()->format("Y-m-d") . ". It's supposed to be greater than arrival date " $entity->getArrivalDate()->format("Y-m-d"));
  117.                 $error true;
  118.             }
  119.             $bookings=$this->entityManager->getRepository(BookingRoom::class)->findByPeriodRoomBook($entity->getArrivalDate()->format("Y-m-d"),$entity->getDepartureDate()->format("Y-m-d"), $entity->getRoom()->getId());
  120.             if(!empty($bookings)){
  121.                 $this->session->getFlashBag()->add("warning""Room " $entity->getRoom() . " is not available on this period " $entity->getArrivalDate()->format("Y-m-d")." - ".$entity->getDepartureDate()->format("Y-m-d").". Total bookings: ".sizeof($bookings));
  122.                 $error true;
  123.             }
  124.             if ($error) {
  125.                 $this->entityManager->remove($entity);
  126.             }else{
  127.                 $transactionRef= new TransactionRef();
  128.                 $transactionRef->amount=$entity->getPayment()->getAmount();
  129.                 $transactionRef->userId=$entity->getUser()->getId();
  130.                 $transactionRef->roomId=$entity->getRoom()->getId();
  131.                 $transactionRef->createdDate=$entity->getCreatedAt()->format("Y-m-d H:i:s");
  132.                 $entity->getPayment()->setTransactionRef(
  133.                     sha1(json_encode($transactionRef))
  134.                 );
  135.                 $token= new Token();
  136.                 $token->amount=$entity->getPayment()->getAmount();
  137.                 $token->booking=$entity->getId();
  138.                 $token->ref$entity->getPayment()->getTransactionRef();
  139.                 $entity->getPayment()->setPaymentToken(
  140.                     base64_encode(json_encode$token))
  141.                 );
  142.                 $entity->setPaymentLink($this->getGeneratePaymentUrl($entity));
  143.                 $entity->setPaymentNotificationLink($this->getNotifyPaymentLink());
  144.                 $this->entityManager->persist($entity);
  145.                 $this->entityManager->flush();
  146.             }
  147.         }
  148.               if(!$error)
  149.                 $this->session->getFlashBag()->add('success', new TranslatableMessage('content_admin.flash_message.create', [
  150.                     '%name%' => (string) $event->getEntityInstance(),
  151.                 ], 'admin'));
  152.                 $log= new Logs();
  153.                 $log->setActivity("create new entity ".$entity);
  154.                 $log->setIpAddress($this->requestStack->getCurrentRequest()->getClientIp());
  155.         $user $this->entityManager->getRepository(User::class)->findOneBy(
  156.             ['id' => $_SESSION["userId"]]
  157.         );
  158.                 $log->setUser($user);
  159.                 $this->entityManager->persist($log);
  160.                 $this->entityManager->flush();
  161.         if($entity instanceof User){
  162.             $entity->setResendMail($this->getResendEmailUrl($entity));
  163.             $this->entityManager->persist($entity);
  164.             $this->entityManager->flush();
  165.         }
  166.         if($entity instanceof Room){
  167.             $serverKey="AAAAOSFzLyc:APA91bEBmPSN8xq2h4vYDs4wW5UfhoMTdy-Y3VclpUqIVkoe4svv5tsBLFxczyqdePX4YoIZ4gKuZxKBwM5MrrjdDG98oi5YwM00roWfuOTio_sc83TC1l5D8zyjfBgaschvw22o8EiK";
  168.                 $host=$this->requestStack->getCurrentRequest()->getBaseUrl();
  169.             $client = new \GuzzleHttp\Client([
  170.                 'headers' => [
  171.                     'Content-Type' => 'application/json',
  172.                     'Authorization' => 'Bearer '.$serverKey
  173.                 ]
  174.             ]);
  175.             $notification= new Notification();
  176.             $notification->setTitle("New Added in ".$entity->getBuilding());
  177.             $notification->setImage($entity->getPicture());
  178.             $notification->setData("Room ".$entity);
  179.             $notification->setMessage("Room ".$entity);
  180.             $notification->setAction("");
  181.             $response $client->post('https://fcm.googleapis.com/fcm/send', [
  182.                 "json" => [
  183.                     'to' => '/topics/loger',
  184.                     'data' => [
  185.                         "title"=>$notification->getTitle(),
  186.                         "image"=>$notification->getImage(),
  187.                         "data"=>$notification->getData(),
  188.                         "message"=>$notification->getMessage(),
  189.                         "action"=>$notification->getAction(),
  190.                         "action_destination"=>$notification->getActionDestination(),
  191.                     ]
  192.                 ]
  193.             ]);
  194.             $responseBodies=json_decode($response->getBody()->getContents());
  195.         }
  196.         if($entity instanceof NotificationPush){
  197.             $serverKey="AAAAOSFzLyc:APA91bEBmPSN8xq2h4vYDs4wW5UfhoMTdy-Y3VclpUqIVkoe4svv5tsBLFxczyqdePX4YoIZ4gKuZxKBwM5MrrjdDG98oi5YwM00roWfuOTio_sc83TC1l5D8zyjfBgaschvw22o8EiK";
  198.             $host=$this->requestStack->getCurrentRequest()->getBaseUrl();
  199.             $client = new \GuzzleHttp\Client([
  200.                 'headers' => [
  201.                     'Content-Type' => 'application/json',
  202.                     'Authorization' => 'Bearer '.$serverKey
  203.                 ], 'verify'=>false
  204.             ]);
  205.             $notification= new Notification();
  206.             $notification->setTitle($entity->getTitle());
  207.             $notification->setImage($entity->getImage());
  208.             $notification->setData($entity->getMessage());
  209.             $notification->setMessage($entity->getMessage());
  210.             $notification->setAction("");
  211.             foreach ($entity->getFirebaseToken() as $token) {
  212.                 $response $client->post('https://fcm.googleapis.com/fcm/send', [
  213.                     "json" => [
  214.                         'to' => $token->getDeviseId(),
  215.                         'data' => [
  216.                             "title"=>$notification->getTitle(),
  217.                             "image"=>$notification->getImage(),
  218.                             "data"=>$notification->getData(),
  219.                             "message"=>$notification->getMessage(),
  220.                             "action"=>$notification->getAction(),
  221.                             "action_destination"=>$notification->getActionDestination(),
  222.                         ]
  223.                     ]
  224.                 ]);
  225.                 $responseBodies=json_decode($response->getBody()->getContents());
  226.                 try {
  227.                     if(($responseBodies->success)){
  228.                         $this->session->getFlashBag()->add('info'"Notification broacasted with id: ".$responseBodies->multicast_id);
  229.                         $entity->setHasBeenSent(true);
  230.                     }else{
  231.                         $entity->setHasBeenSent(false);
  232.                     }
  233.                 }catch (Exception $exception){
  234.                 }
  235.             }
  236.         }
  237.     }
  238.     public function onBeforeCreateEntity(BeforeEntityPersistedEvent $event){
  239.         $entity $event->getEntityInstance();
  240.         if($entity instanceof User) {
  241.             $encoded $this->encoder->hashPassword($entity$entity->getPlainPassword());
  242.             $entity->setPassword($encoded);
  243.             $entity->setUsername($entity->getEmail());
  244.             $this->entityManager->persist($entity);
  245.             $this->entityManager->flush();
  246.             // generate a signed url and email it to the user
  247.             $this->emailVerifier->sendEmailConfirmation('app_verify_email'$entity,
  248.                 (new TemplatedEmail())
  249.                     ->from(new Address('noreply@loger.cm''LOGER CM - NO REPLY'))
  250.                     ->to($entity->getEmail())
  251.                     ->subject('Please Confirm your Email')
  252.                     ->htmlTemplate('registration/confirmation_email.html.twig')
  253.             );
  254.             // do anything else you need here, like send an email
  255.             // @TODO Change the redirect on success and handle or remove the flash message in your templates
  256.             $this->session-> getFlashBag()->add('success''Email send to verify the mail address.');
  257.         }
  258.     }
  259.     public function onAfterBuiltEntity(AfterEntityBuiltEvent $event){
  260.         $entity $event->getEntity();
  261.     }
  262.     public function onUpdateEntity(BeforeEntityUpdatedEvent $event){
  263.         $entity $event->getEntityInstance();
  264.             $this->session->getFlashBag()->add('success', new TranslatableMessage('content_admin.flash_message.update', [
  265.                 '%name%' => (string) $entity,
  266.             ], 'admin'));
  267.         $log= new Logs();
  268.         $log->setActivity("update entity ".$entity);
  269.         $log->setIpAddress($this->requestStack->getCurrentRequest()->getClientIp());
  270.         $user $this->entityManager->getRepository(User::class)->findOneBy(
  271.             ['id' => $_SESSION["userId"]]
  272.         );
  273.         $log->setUser($user);
  274.         $this->entityManager->persist($log);
  275.         $this->entityManager->flush();
  276.         if($entity instanceof Country){
  277.             $this->session->getFlashBag()->add('info'"searching towns in progress...");
  278.             $this->getTowns($entity);
  279.         }
  280.         if($entity instanceof User){
  281.             $entity->setResendMail($this->getResendEmailUrl($entity));
  282.             $entity->setUpdateAt(new \DateTimeImmutable());
  283.             $this->entityManager->persist($entity);
  284.             $this->entityManager->flush();
  285.         }
  286.         if($entity instanceof BookingRoom){
  287.             $transactionRef= new TransactionRef();
  288.             $transactionRef->amount=$entity->getPayment()->getAmount();
  289.             $transactionRef->userId=$entity->getUser()->getId();
  290.             $transactionRef->roomId=$entity->getRoom()->getId();
  291.             $transactionRef->createdDate=$entity->getCreatedAt()->format("Y-m-d H:i:s");
  292.             $entity->getPayment()->setTransactionRef(
  293.                 sha1(json_encode($transactionRef))
  294.             );
  295.             $token= new Token();
  296.             $token->amount=$entity->getPayment()->getAmount();
  297.             $token->booking=$entity->getId();
  298.             $token->ref$entity->getPayment()->getTransactionRef();
  299.             $entity->getPayment()->setPaymentToken(
  300.                 base64_encode(json_encode$token))
  301.             );
  302.             $entity->setPaymentLink($this->getGeneratePaymentUrl($entity));
  303.             $entity->setPaymentNotificationLink($this->getNotifyPaymentLink());
  304.             $this->entityManager->persist($entity);
  305.             $this->entityManager->flush();
  306.         }
  307.         if($entity instanceof Room){
  308.             $serverKey="AAAAOSFzLyc:APA91bEBmPSN8xq2h4vYDs4wW5UfhoMTdy-Y3VclpUqIVkoe4svv5tsBLFxczyqdePX4YoIZ4gKuZxKBwM5MrrjdDG98oi5YwM00roWfuOTio_sc83TC1l5D8zyjfBgaschvw22o8EiK";
  309.             $host=$this->requestStack->getCurrentRequest()->getBaseUrl();
  310.             $client = new \GuzzleHttp\Client([
  311.                 'headers' => [
  312.                     'Content-Type' => 'application/json',
  313.                     'Authorization' => 'Bearer '.$serverKey
  314.                 ], 'verify'=>false
  315.             ]);
  316.             $notification= new Notification();
  317.             $notification->setTitle("New update in ".$entity->getBuilding());
  318.             $notification->setImage($entity->getPicture());
  319.             $notification->setData("Room ".$entity);
  320.             $notification->setMessage("Room ".$entity);
  321.             $notification->setAction("");
  322.             $response $client->post('https://fcm.googleapis.com/fcm/send', [
  323.                 "json" => [
  324.                     'to' => '/topics/loger',
  325.                     'data' => [
  326.                         "title"=>$notification->getTitle(),
  327.                         "image"=>$notification->getImage(),
  328.                         "data"=>$notification->getData(),
  329.                         "message"=>$notification->getMessage(),
  330.                         "action"=>$notification->getAction(),
  331.                         "action_destination"=>$notification->getActionDestination(),
  332.                     ]
  333.                 ]
  334.             ]);
  335.             $responseBodies=json_decode($response->getBody()->getContents());
  336.             $this->session->getFlashBag()->add('info'"Notification broacasted with id: ".$responseBodies->message_id);
  337.         }
  338.     }
  339.     public function onDeleteEntity(BeforeEntityDeletedEvent $event){
  340.         $entity=$event->getEntityInstance();
  341.         $this->session->getFlashBag()->add('success', new TranslatableMessage('content_admin.flash_message.delete', [
  342.             '%name%' => (string) $entity,
  343.         ], 'admin'));
  344.         $log= new Logs();
  345.         $log->setActivity("delete entity ".$entity);
  346.         $log->setIpAddress($this->requestStack->getCurrentRequest()->getClientIp());
  347.         $user $this->entityManager->getRepository(User::class)->findOneBy(
  348.             ['id' => $_SESSION["userId"]]
  349.         );
  350.         $log->setUser($user);
  351.         $this->entityManager->persist($log);
  352.         $this->entityManager->flush();
  353.         if($entity instanceof BookingRoom){
  354.             $entity->getRoom()->setIsFree(true);
  355.             $this->entityManager->persist($entity);
  356.             $this->entityManager->flush();
  357.         }
  358.     }
  359.     public function getTowns(Country $country){
  360.         $client = new \GuzzleHttp\Client();
  361.         try {
  362.             $response $client->request('GET''https://wft-geo-db.p.rapidapi.com/v1/geo/cities?countryIds='.$country->getCode()."&offset=".$country->getOffset()."&limit=5", [
  363.                 'headers' => [
  364.                     'X-RapidAPI-Host' => 'wft-geo-db.p.rapidapi.com',
  365.                     'X-RapidAPI-Key' => 'd01923dc5amsh8cc5a1094d152c2p117a73jsneebdb0db3f67',
  366.                 ],
  367.                 'verify' => false
  368.             ]);
  369.             $responseBodies=json_decode($response->getBody()->getContents());
  370.             $offset=$country->getOffset()+sizeof($responseBodies->data);
  371.             foreach ($responseBodies->data  as $responseTown){
  372.                 $town=new Town();
  373.                 $town->setCountry($country);
  374.                 $town->setTownName($responseTown-> name);
  375.                 $town->setLatitude($responseTown-> latitude);
  376.                 $town->setLongitude($responseTown-> longitude);
  377.                 $town->setRegion($responseTown-> longitude);
  378.                 $town->setPopulation($responseTown-> population);
  379.                 $town->setIsCapital(false);
  380.                 $dbTown=$this->entityManager->getRepository(Town::class)->findOneByName($responseTown-> name);
  381.                 if (empty($dbTown)) {
  382.                     $this->entityManager->persist($town);
  383.                     $this->entityManager->flush();
  384.                     $this->session->getFlashBag()->add('success'$town." added");
  385.                 }else{
  386.                     $dbTown->setLatitude($responseTown-> latitude);
  387.                     $dbTown->setLongitude($responseTown-> longitude);
  388.                     $dbTown->setPopulation($responseTown-> population);
  389.                     $dbTown->setRegion($responseTown-> region);
  390.                     $this->entityManager->persist($dbTown);
  391.                     $this->entityManager->flush();
  392.                     $offset--;
  393.                     $this->session->getFlashBag()->add('success'$town." updated");
  394.                 }
  395.             }
  396.             $country->setOffset$offset);
  397.             $this->entityManager->persist($country);
  398.             if($offset<$responseBodies->metadata->totalCount){
  399.                 $this->getTowns($country);
  400.             }
  401.         }catch (RequestException $exception){
  402.         }
  403.     }
  404.     public function getResendEmailUrl(User $user): string
  405.     {
  406.         return $this->urlGenerator->generate(self::RESEND_MAIL,["user"=>$user->id]);
  407.     }
  408. public function getGeneratePaymentUrl(BookingRoom $bookingRoom): string
  409.     {
  410.         return $this->urlGenerator->generate(self::GENERATE_PAYMENT,["token"=>$bookingRoom->getPayment()->getPaymentToken()]);
  411.     }
  412. public function getNotifyPaymentLink(): string
  413.     {
  414.         return $this->urlGenerator->generate(self::NOTIFY_PAYMENT);
  415.     }
  416. }