src/EventListener/UserRequestListener.php line 186

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Entity\Subscription;
  4. use App\Entity\SubscriptionType;
  5. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  6. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  7. use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
  8. use App\Model\User;
  9. use App\Helper\Tools;
  10. use App\Repository\UserRepository;
  11. use DateInterval;
  12. use DateTime;
  13. use DateTimeImmutable;
  14. use Symfony\Component\HttpFoundation\RedirectResponse;
  15. use Symfony\Component\HttpKernel\Event\RequestEvent;
  16. use Symfony\Component\HttpKernel\KernelInterface;
  17. use Symfony\Component\Routing\RouterInterface;
  18. class UserRequestListener
  19. {
  20.     /**
  21.      * @var AuthorizationChecker
  22.      */
  23.     protected $authChecker;
  24.     /**
  25.      * @var TokenStorageInterface
  26.      */
  27.     protected $tokenStorage;
  28.     /**
  29.      * @var SessionInterface
  30.      */
  31.     protected $session;
  32.     /**
  33.      * @var UserRepository
  34.      */
  35.     protected $userRepository;
  36.     /**
  37.      * @var KernelInterface
  38.      */
  39.     protected $kernel;
  40.     /**
  41.      * @var RouterInterface
  42.      */
  43.     protected $router;
  44.     public function __construct(
  45.         AuthorizationChecker $authChecker,
  46.         TokenStorageInterface $tokenStorage,
  47.         SessionInterface $session,
  48.         UserRepository $userRepository,
  49.         KernelInterface $kernel,
  50.         RouterInterface $router
  51.         ) {
  52.         $this->authChecker $authChecker;
  53.         $this->tokenStorage $tokenStorage;
  54.         $this->authChecker $authChecker;
  55.         $this->session $session;
  56.         $this->userRepository $userRepository;
  57.         $this->kernel $kernel;
  58.         $this->router $router;
  59.     }
  60.     /**
  61.      * @return Kernel
  62.      */
  63.     public function getKernel()
  64.     {
  65.         return $this->kernel;
  66.     }
  67.     public function endingDate($subscriptionType)
  68.     {
  69.         $dateNow = new DateTime();
  70.         $endingDate $dateNow;
  71.         if ('annuel' === $subscriptionType->getPeriod()) {
  72.             $endingDate $dateNow->add(new DateInterval('P1Y'));
  73.         } else {
  74.             $endingDate $dateNow->add(new DateInterval('P1M'));
  75.         }
  76.         return DateTimeImmutable::createFromMutable($endingDate);
  77.     }
  78.     public function checkSubscription($user)
  79.     {
  80.         $stripe = new \Stripe\StripeClient($this->getKernel()->getContainer()->getParameter('STRIPE_SECRET_KEY_LIVE'));
  81.         $em $this->getKernel()->getContainer()->get('doctrine.orm.default_entity_manager');
  82.         if (!is_string($user)) {
  83.             if ($user->getStripeId()) {
  84.                 $customer $stripe->customers->retrieve(
  85.                 $user->getStripeId(),
  86.                 ['expand' => ['subscriptions']]
  87.                 );
  88.                 if ($customer->subscriptions) {
  89.                     if ($customer->subscriptions->data) {
  90.                         $subscription $customer->subscriptions->data;
  91.                         $annuelOrMensuel 'year' === $subscription[0]->plan->interval Tools::YEAR Tools::MONTH;
  92.                         //add subscription in DB if there is a subscription on stripe
  93.                         if (!== count($subscription) && 'active' === $customer->subscriptions->data[0]->status) {
  94.                             if (null === $user->getSubscription()) {
  95.                                 $newSubscription = new Subscription();
  96.                                 $subscriptionType $em->getRepository(SubscriptionType::class)->findOneBy(['name' => $annuelOrMensuel]);
  97.                                 $newSubscription->setSubscriptionType($subscriptionType);
  98.                                 $newSubscription->setEndingAt($this->endingDate($subscriptionType));
  99.                                 $user->setSubscription($newSubscription);
  100.                                 $em->persist($user);
  101.                                 $em->persist($newSubscription);
  102.                                 $em->flush();
  103.                             } else {
  104.                                 //set new subscription endingDate if endingDate before now
  105.                                 if ($user->getSubscription()->getEndingAt() < new DateTime()) {
  106.                                     $user->getSubscription()->setEndingAt($this->endingDate($user->getSubscription()->getSubscriptionType()));
  107.                                     $em->persist($user);
  108.                                     $em->flush();
  109.                                 }
  110.                                 //need to release subscription schedule if exists for later edit or cancel subscription
  111.                                 if ($subscription[0]->schedule) {
  112.                                     $stripe->subscriptionSchedules->release(
  113.                                 $customer->subscriptions->data[0]->schedule,
  114.                                 []
  115.                             );
  116.                                 }
  117.                                 //during change of subscription to pass from annuel to mensuel or revert
  118.                                 if ($annuelOrMensuel !== $user->getSubscription()->getSubscriptionType()->getPeriod()) {
  119.                                     $subscriptionType $em->getRepository(SubscriptionType::class)->findOneBy(['name' => $annuelOrMensuel]);
  120.                                     $subscriptionToEdit $em->getRepository(Subscription::class)->findOneBy(['id' => $user->getSubscription()->getId()]);
  121.                                     $subscriptionToEdit->setSubscriptionType($subscriptionType);
  122.                                     $subscriptionToEdit->setCreatedAt(new DateTime());
  123.                                     $subscriptionToEdit->setEndingAt($this->endingDate($subscriptionType));
  124.                                     $em->persist($subscriptionToEdit);
  125.                                     $em->flush();
  126.                                 }
  127.                             }
  128.                         } else {
  129.                             //remove subscription if no subscription on stripe
  130.                             if ($user->getSubscription()) {
  131.                                 $user->setSubscription(null);
  132.                                 $em->persist($user);
  133.                                 $em->flush();
  134.                             }
  135.                         }
  136.                     } else {
  137.                         //remove subscription if no subscription on stripe
  138.                         if ($user->getSubscription()) {
  139.                             $user->setSubscription(null);
  140.                             $em->persist($user);
  141.                             $em->flush();
  142.                         }
  143.                     }
  144.                 }
  145.             } else {
  146.                 //add stripe id in bdd if preset in stripe for current user
  147.                 $customer $stripe->customers->search([
  148.                     'query' => 'email:\''.$user->getEmail().'\'',
  149.                   ]);
  150.                 if ($customer && 'ROLE_CLIENT' === $user->getRoles()[0]) {
  151.                     $user->setStripeId($customer->data[0]->id);
  152.                     $em->persist($user);
  153.                     $em->flush();
  154.                 }
  155.             }
  156.         }
  157.     }
  158.     public function onKernelRequest(RequestEvent $event)
  159.     {
  160.         if (!$event->isMainRequest()) {
  161.             // don't do anything if it's not the main request
  162.             return;
  163.         }
  164.         $accessToken $this->tokenStorage->getToken();
  165.         $currentRoute $event->getRequest()->get('_route');
  166.         if (!$accessToken) {
  167.             return;
  168.         }
  169.         // When logging the current user to the admin, we don't need to make all the checks underneath
  170.         if ('admin_dashboard' === $currentRoute) {
  171.             return;
  172.         }
  173.         /** @var User $user */
  174.         $user $accessToken->getUser();
  175.         if ('object' == gettype($user)) {
  176.             if ($this->session->get('sessionSecret') !== $user->getSessionSecret()) {
  177.                 // Logging user out.
  178.                 $this->tokenStorage->setToken(null);
  179.                 // Invalidating the session.
  180.                 $this->session->invalidate();
  181.             }
  182.         }
  183.         $this->checkSubscription($user);
  184.         $routesToIgnore = ['app_api_payment_getstripeinfos''app_my_account''app_api_payment_newsubscription''app_api_payment_updatecard',
  185.         'app_api_payment_subscriptiontype''app_api_payment_payments', ];
  186.         if ('anon.' !== $user) {
  187.             if (!$user->getSubscription() && 'ROLE_CLIENT' === $user->getRoles()[0]) {
  188.                 if (!in_array($currentRoute$routesToIgnore)) {
  189.                     $response = new RedirectResponse($this->router->generate('app_my_account'));
  190.                     $event->setResponse($response);
  191.                 }
  192.             }
  193.         }
  194.     }
  195. }