Skip to content
Snippets Groups Projects
Select Git revision
  • 896ae65606405025e2d6e636aee36fc47527ec4c
  • master default
2 results

NotificationController.php

Blame
  • user avatar
    Jeremy Guiselin authored
    896ae656
    History
    NotificationController.php 4.71 KiB
    <?php
    /**
     * Created by PhpStorm.
     * User: jeremyguiselin
     * Date: 23/09/2016
     * Time: 08:22
     */
    
    namespace BackendBundle\Controller;
    
    use BackendBundle\Entity\Notification;
    use Doctrine\ORM\Tools\Pagination\Paginator;
    use GuzzleHttp\Client;
    use GuzzleHttp\Exception\BadResponseException;
    use GuzzleHttp\Exception\ClientException;
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    
    class NotificationController extends Controller
    {
    
        const NOTIFICATION_API_URL = 'https://fcm.googleapis.com/fcm/send';
        const SERVER_KEY = "AAAA6m6eLXI:APA91bHDsojOIQaWHX5nGNGS9Thyn6MAZZvLvvfEEdWmzbOjD7lYqkghcER69wRkiaRb4zfEQ5P5V8ckdVjGUf58CmMqYNhsRPCy75OeugN85oHCOCBvYn7I7czIsy2pScYKgB2eWC0wRxsyw7-iEMwpzf6eZFWM8w";
        const SENDER_ID = "1006878207346";
        const DEFAULT_PAGE_RESULT = 20;
    
        /**
         * @param Request $request
         * @return Response
         *
         * @Route("/admin/notification/create")
         */
        public function createAction(Request $request)
        {
    
            $notification = new Notification();
    
            $form = $this->createForm('BackendBundle\\Form\\NotificationType', $notification);
    
            if ($request->getMethod() === Request::METHOD_POST) {
                $form->handleRequest($request);
    
                if ($form->isValid()) {
    
                    $devices = $this->getDoctrine()->getRepository('BackendBundle:Device')->findAll();
    
                    $client = new Client();
    
                    foreach ($devices as $device) {
                        if ($device->getLocale() === 'fr') {
                            $message = [
                                'notification' => [
                                    'title' => $notification->getFrenchTitle(),
                                    'body' => $notification->getFrenchContent(),
    				"content_available" => 1
                                ],
                                'to' => $device->getToken(),
    			    'priority' => 'high'
    
                            ];
                        } else {
                            $message = [
                                'notification' => [
                                    'title' => $notification->getEnglishTitle(),
                                    'body' => $notification->getEnglishContent(),
    			        "content_available" => 1
                                ],
                                'to' => $device->getToken(),
    			    'priority' => 'high'
                            ];
                        }
    
    		    if ($device->getToken() !== 'BLACKLISTED') {
    
                            $client->request('POST', self::NOTIFICATION_API_URL, [
                                'body' => json_encode($message),
                                'headers'=> [
                                    'Authorization' => 'key='.self::SERVER_KEY,
                                    'Content-Type'  => 'application/json',
                                ]
                            ]);
    		    }
                    }
    
                    $notification->setDate(new \DateTime());
                    $em = $this->getDoctrine()->getEntityManager();
                    $em->persist($notification);
                    $this->getDoctrine()->getRepository('BackendBundle:NotificationOnDevice')->updateStatusOnAllDevices($devices, $notification);
                    $this->addFlash('success', 'La notification a bien été envoyée');
                    return $this->redirectToRoute('backend_notification_list', ['page' => 1]);
                }
            }
    
            return $this->render('@Backend/notification/create.html.twig',[
                'form' => $form->createView()
            ]);
        }
    
        /**
         * @param Request $request
         * @param int $page
         * @return Response
         *
         * @Route("/admin/notification/list/{page}")
         */
        public function listAction(Request $request, int $page)
        {
            $em = $this->getDoctrine()->getManager();
    
            if (!isset($page)) {
                $page = 1;
            }
    
            $repository = $em->getRepository('BackendBundle:Notification');
    
            $query = $repository->getAll();
    
            $firstResult = $page === 1 ? 0 : self::DEFAULT_PAGE_RESULT * ($page-1) - 1;
    
            $pagination = new Paginator($query);
    
            $totalItems = count($pagination);
    
            $pagesCount = ceil($totalItems / self::DEFAULT_PAGE_RESULT) >= 1 ? ceil($totalItems / self::DEFAULT_PAGE_RESULT) : 1;
    
            $pagination->getQuery()
                ->setMaxResults(self::DEFAULT_PAGE_RESULT)
                ->setFirstResult($firstResult)
            ;
    
            return $this->render(
                'BackendBundle:notification:list.html.twig',
                [
                    'elements' => $pagination,
                    'countPages' => $pagesCount,
                    'page' => $page,
                    'name' => 'notification'
                ]
            );
        }
    
    }