Exemplo n.º 1
0
 /**
  * @Route("/xhr/getTimetable/{id}")
  * @Template("canoUEKCBundle:Autocomplete:index.html.twig")
  */
 public function getTimetable($id)
 {
     //        $q1 = $this->getDoctrine()->getRepository('canoUEKCBundle:GroupEnt')->createQueryBuilder('groupEnt')
     //            ->select('groupEnt.name')
     //            ->where('groupEnt.id = :id')
     //            ->setParameter('id', $id)
     //            ->getQuery()->getResult();
     $q = $this->getDoctrine()->getRepository('canoUEKCBundle:GroupEnt')->createQueryBuilder('groupEnt')->select('groupEnt, classes')->leftJoin('groupEnt.classes', 'classes')->where('groupEnt.id = :subCompanyId')->setParameter("subCompanyId", $id)->getQuery()->getResult();
     $classes = $q[0]->getClasses();
     $data = [];
     $em = $this->getDoctrine()->getManager();
     //        ld($classes[0]->getId());
     //        die();
     //        $crawlStatus = $em->getRepository('canoUEKCBundle:Classroom')->find($classes[0]->getClassroomId());
     for ($i = 0; $i < count($classes); $i++) {
         $q = $this->getDoctrine()->getRepository('canoUEKCBundle:Teacher')->createQueryBuilder('teacher')->select('teacher.name', 'teacher.lastname')->leftJoin('teacher.classes', 'classes')->where('classes.id = :query')->setParameter('query', $classes[$i]->getId())->getQuery()->getResult();
         //            ld($q[0]['name']);
         //            ;die();
         $data[$i]['YYYY'] = $classes[$i]->getDate()->format("Y");
         $data[$i]['MM'] = $classes[$i]->getDate()->format("m");
         $data[$i]['DD'] = $classes[$i]->getDate()->format("d");
         $data[$i]['startTime'] = $classes[$i]->getStartTime()->format("H:i");
         $data[$i]['endTime'] = $classes[$i]->getEndTime()->format("H:i");
         $data[$i]['classroom'] = $em->getRepository('canoUEKCBundle:Classroom')->find($classes[0]->getClassroomId())->getName();
         $data[$i]['type'] = $em->getRepository('canoUEKCBundle:ClassType')->find($classes[0]->getTypes())->getName();
         $data[$i]['teacher'] = $q[0]['name'] . ' ' . $q[0]['lastname'];
     }
     $response = new JsonResponse();
     $response->setData($data);
     return $response;
 }
Exemplo n.º 2
0
 /**
  * 
  * @Route("/{_locale}/{_code}/statistics/{dataset}.json", requirements={"_locale" = "de|en|es|fr", "_code" = "[a-zA-Z0-9]{10}", "dataset" = "[a-zA-Z0-9_-]+"})
  */
 public function statisticsJsonAction($_code, $dataset, Request $request)
 {
     try {
         $context = $this->getContext($_code, 'statistics');
         $stats = new Statistics($this, $this->account);
         if (preg_match('!^wallet-([0-9]+)$!', $dataset, $m)) {
             $method = 'getDatasetWallet';
             if (method_exists($stats, $method)) {
                 $data = $stats->{$method}($m[1]);
                 if (!empty($data)) {
                     $response = new JsonResponse($data);
                 }
             }
         } else {
             $method = 'getDataset' . $dataset;
             if (method_exists($stats, $method)) {
                 $response = new JsonResponse($stats->{$method}());
             }
         }
         if (isset($response)) {
             $response->setMaxAge(900);
             $response->setExpires(new \DateTime('@' . (time() + 900)));
             $response->setPublic();
             return $response;
         }
     } catch (\Exception $ex) {
         return new JsonResponse(['error' => $ex->getMessage()]);
     }
 }
 /**
  * @param GetResponseForExceptionEvent $event
  */
 public function onKernelException(GetResponseForExceptionEvent $event)
 {
     $exception = $event->getException();
     $code = $exception->getCode();
     $debug = array('class' => get_class($exception), 'code' => $code, 'message' => $exception->getMessage());
     $this->logger->error(print_r($debug, true));
     // HttpExceptionInterface est un type d'exception spécial qui
     // contient le code statut et les détails de l'entête
     if ($exception instanceof NotFoundHttpException) {
         $data = array('error' => array('code' => $code ? $code : -3, 'message' => $exception->getMessage()));
         $response = new JsonResponse($data);
         $response->setStatusCode($exception->getStatusCode());
         $response->headers->replace($exception->getHeaders());
         $response->headers->set('Content-Type', 'application/json');
     } elseif ($exception instanceof HttpExceptionInterface) {
         $data = array('error' => array('code' => $code ? $code : -2, 'message' => $exception->getMessage()));
         $response = new JsonResponse($data);
         $response->setStatusCode($exception->getStatusCode());
         $response->headers->replace($exception->getHeaders());
         $response->headers->set('Content-Type', 'application/json');
     } else {
         $data = array('error' => array('code' => $code ? $code : -1, 'message' => 'Internal Server Error / ' . $exception->getMessage()));
         $response = new JsonResponse($data);
         $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
     }
     // envoie notre objet réponse modifié à l'évènement
     $event->setResponse($response);
 }
Exemplo n.º 4
0
 public function RefreshNotificationAction($id, Request $request)
 {
     if ($request->isXmlHttpRequest()) {
         // si on appele depuis une requette ajax
         $em = $this->getDoctrine()->getManager();
         $Allnotifs = $em->getRepository('OCNotificationBundle:Notification')->findByPourAgent($id);
         if ($Allnotifs) {
             $notifs = array();
             foreach ($Allnotifs as $notif) {
                 $interval = $notif->getDateCreation()->diff(new \DateTime('now'));
                 if ($interval->format('%a') == "0") {
                     $date = "aujourd'hui";
                 } elseif ($interval->format('%a') == "1") {
                     $date = "hier";
                 } else {
                     $date = $interval->format('%a jours');
                 }
                 if ($notif->getEventAssocie() !== null) {
                     $nom_agent = $notif->getEventAssocie()->getAgent()->getNomCanonique();
                 } else {
                     $nom_agent = $notif->getHSFAssocie()->getAgent()->getNomCanonique();
                 }
                 $notifs[$notif->getId()] = array($notif->getId(), $nom_agent, $notif->getTitle(), $notif->getVisionee(), $date);
             }
         } else {
             $notif = null;
         }
         //var_dump($notifs);
         //die();
         $response = new JsonResponse();
         return $response->setData(array('notifs' => $notifs));
     } else {
         throw new Exception("Vous n'etes pas censés être ici ! Cassez vous !");
     }
 }
 /**
  * @Route("/admin/testimonials/jsondata", name="admin_testimonials_jsondata")
  */
 public function JsonData(Request $request)
 {
     $sortColumn = $request->get('sidx');
     $sortDirection = $request->get('sord');
     $pageSize = $request->get('rows');
     $page = $request->get('page');
     $callback = $request->get('callback');
     $repo = $this->getDoctrineRepo('AppBundle:Testimonial');
     $dataRows = $repo->getGridOverview($sortColumn, $sortDirection, $pageSize, $page);
     $rowsCount = $repo->countAll();
     $pagesCount = ceil($rowsCount / $pageSize);
     $rows = array();
     // rows as json result
     foreach ($dataRows as $dataRow) {
         // build single row
         $row = array();
         $row['id'] = $dataRow->getId();
         $cell = array();
         $i = 0;
         $cell[$i++] = '';
         $cell[$i++] = $dataRow->getId();
         $cell[$i++] = $dataRow->getName();
         $cell[$i++] = $dataRow->getAge();
         $cell[$i++] = $dataRow->getPlace();
         $cell[$i++] = $dataRow->getPosition();
         $row['cell'] = $cell;
         array_push($rows, $row);
     }
     $result = array('records' => $rowsCount, 'page' => $page, 'total' => $pagesCount, 'rows' => $rows);
     $resp = new JsonResponse($result, JsonResponse::HTTP_OK);
     $resp->setCallback($callback);
     return $resp;
 }
Exemplo n.º 6
0
 /**
  * @Secure(roles="ROLE_USER, ROLE_ADMINISTRATOR")
  */
 public function updateAction(Request $request)
 {
     $params = [];
     $requestBody = $this->get("request")->getContent();
     if (!empty($requestBody)) {
         $params = json_decode($requestBody, true);
         $em = $this->getDoctrine()->getManager();
         $user = $this->get('security.context')->getToken()->getUser();
         //$slices = explode(':', $params['grid']);
         //array_pop($slices);
         $grid = $params['grid'];
         $fields = implode('|', $params['fields']);
         //$layout = $this->get('app_core.grid_layout_repository')
         $layout = $em->getRepository('CoreBundle:GridLayout')->findUserLayout($grid, $user->getId());
         if (is_null($layout)) {
             $layout = new GridLayout();
         }
         $layout->setUser($user);
         $layout->setGrid($grid);
         $layout->setLayout($fields);
         $em->persist($layout);
         $em->flush();
     }
     $response = new JsonResponse();
     $responseBody = [];
     $response->setData($responseBody);
     return $response;
 }
Exemplo n.º 7
0
 /**
  * Process Ajax Form to add a simple category (name and parent category)
  *
  * @param Request $request
  *
  * @return string
  */
 public function addSimpleCategoryFormAction(Request $request)
 {
     $response = new JsonResponse();
     $tools = $this->container->get('prestashop.adapter.tools');
     $shopContext = $this->container->get('prestashop.adapter.shop.context');
     $shopList = $shopContext->getShops(false, true);
     $currentIdShop = $shopContext->getContextShopID();
     $form = $this->createFormBuilder()->add('category', 'PrestaShopBundle\\Form\\Admin\\Category\\SimpleCategory')->getForm();
     $form->handleRequest($request);
     if ($form->isValid()) {
         $data = $form->getData();
         $_POST = ['submitAddcategory' => 1, 'name_1' => $data['category']['name'], 'id_parent' => $data['category']['id_parent'], 'link_rewrite_1' => $tools->link_rewrite($data['category']['name']), 'active' => 1, 'checkBoxShopAsso_category' => $currentIdShop ? [$currentIdShop => $currentIdShop] : $shopList];
         $adminCategoryController = $this->container->get('prestashop.adapter.admin.controller.category')->getInstance();
         if ($category = $adminCategoryController->processAdd()) {
             $response->setData(['category' => $category]);
         }
         if ($request->query->has('id_product')) {
             $productAdapter = $this->get('prestashop.adapter.data_provider.product');
             $product = $productAdapter->getProduct($request->query->get('id_product'));
             $product->addToCategories($category->id);
             $product->save();
         }
     } else {
         $response->setStatusCode(400);
         $response->setData($this->getFormErrorsForJS($form));
     }
     return $response;
 }
Exemplo n.º 8
0
 public function dbAction(Db $db, JsonResponse $response)
 {
     $conn = $db->getConnection();
     $sql = "SELECT * FROM test";
     $stmt = $conn->query($sql);
     return $response->setData($stmt->fetchAll());
 }
 /**
  * @inheritdoc
  */
 public function start(Request $request, AuthenticationException $authException = null)
 {
     $response = new JsonResponse();
     $response->setStatusCode(401);
     $response->setData(['ok' => false, 'error' => 'Accessing this resource requires authorization']);
     return $response;
 }
Exemplo n.º 10
0
 public function findReceiverAction()
 {
     $em = $this->getDoctrine()->getManager();
     $name_receiver = $em->getRepository('DBdbBundle:User')->findAllUserByName();
     $response = new JsonResponse();
     return $response->setData(array('name_receiver' => $name_receiver));
 }
 /**
  * Controller to return the access token when a refresh token is provided.
  *
  * @todo: Get some flood protection for this, since the request is uncacheable
  * because of the expire counter. Also, there has to be some other better way
  * to render JSON. Investigate that too!
  */
 public function refresh()
 {
     $account = $this->currentUser()->getAccount();
     // If the account is not a token account, then bail.
     if (!$account instanceof TokenAuthUserInterface) {
         // TODO: Set the error headers appropriately.
         return NULL;
     }
     $refresh_token = $account->getToken();
     if (!$refresh_token || !$refresh_token->isRefreshToken()) {
         // TODO: Set the error headers appropriately.
         return NULL;
     }
     // Find / generate the access token for this refresh token.
     $access_token = $refresh_token->get('access_token_id')->entity;
     if (!$access_token || $access_token->get('expire')->value < REQUEST_TIME) {
         // If there is no token to be found, refresh it by generating a new one.
         $values = ['expire' => $refresh_token::defaultExpiration(), 'user_id' => $refresh_token->get('user_id')->target_id, 'auth_user_id' => $refresh_token->get('auth_user_id')->target_id, 'resource' => $access_token ? $access_token->get('resource')->target_id : 'global', 'created' => REQUEST_TIME, 'changed' => REQUEST_TIME];
         /* @var AccessTokenInterface $access_token */
         $access_token = $this->entityManager()->getStorage('access_token')->create($values);
         // This refresh token is no longer needed.
         $refresh_token->delete();
         // Saving this token will generate a refresh token for that one.
         $access_token->save();
     }
     $this->response->setData($this->normalize($access_token));
     return $this->response;
 }
Exemplo n.º 12
0
 public function updateAction()
 {
     $em = $this->getDoctrine()->getManager();
     $repoLignesCmd = $em->getRepository("Gestion\\ArticlesBundle\\Entity\\LignesCommande");
     $designation = $this->get('request')->request->get('designation');
     // ok
     $prixTTC = $this->get('request')->request->get('prixTTC');
     // ok
     $detail = $this->get('request')->request->get('detail');
     // ok
     $idLigneCmd = $this->get('request')->request->get('idLgnCmd');
     // ok
     $LigneCmd = $repoLignesCmd->findOneById($idLigneCmd);
     if (isset($designation)) {
         $LigneCmd->setDesignation($designation);
     } elseif (isset($prixTTC)) {
         $newHT = $prixTTC / ($LigneCmd->getTva() / 100 + 1);
         $LigneCmd->setPrixHt($newHT);
     } elseif (isset($detail)) {
         $LigneCmd->setDetail($detail);
     }
     $em->persist($LigneCmd);
     $em->flush();
     $response = new JsonResponse();
     return $response->setData(array('designation' => $designation, 'designation 2' => $LigneCmd->getDesignation(), 'prixTTC' => $prixTTC, 'idLgnCmd' => $idLigneCmd, 'detail' => $detail));
 }
Exemplo n.º 13
0
 /**
  * Building error message
  *
  * @param string $message
  */
 private function buildErrorMessage($message)
 {
     $response = new JsonResponse();
     $response->setData(['error' => $message]);
     $response->send();
     die;
 }
 /**
  * @Route("/chat-api/message")
  */
 public function postMessage(Request $request)
 {
     $message = new ChatMessage();
     $message->setUsername($request->get('username'))->setText($request->get('chat_text'))->setTimestamp(new \DateTime());
     $em = $this->getDoctrine()->getManager();
     $em->persist($message);
     $em->flush();
     // Uncomment this to publish to redis and use Ratchet or Faye
     // $data = [
     //   'event' => 'new-message',
     //   'data' => $message
     // ];
     // $jsonContent = json_encode($data);
     // $redis = new Client('tcp://127.0.0.1:6379');
     // $redis->publish('chat', $jsonContent);
     // Uncomment this to use Pusher
     // $pusher = $this->container->get('lopi_pusher.pusher');
     // $pusher->trigger(
     //   'chat',
     //   'new-message',
     //   $message
     // );
     $response = new JsonResponse();
     $response->setData($message);
     return $response;
 }
Exemplo n.º 15
0
 /**
  * @Route("/evento/get", name="get_event")
  */
 public function retrieveEvent()
 {
     $request = Request::createFromGlobals();
     $from = $request->query->get('from');
     $to = $request->query->get('to');
     if ($from && $to) {
         $em = $this->getDoctrine()->getManager();
         $q = "SELECT e FROM AppBundle\\Entity\\Evento e WHERE (e.fechainicio>=:from AND e.fechainicio<=:to) OR (e.fechafin>=:from AND e.fechafin<=:to)";
         $query = $em->createQuery($q);
         $query->setParameter('from', date("Y/m/d H:i:s", $from / 1000));
         $query->setParameter('to', date("Y/m/d H:i:s", $to / 1000));
         $events = $query->getResult();
         $jevents = array();
         foreach ($events as $ev) {
             $jevents[] = array("id" => $ev->getIdEvento(), "title" => $ev->getDescripcion(), "url" => "http://example.com", "class" => "event-important", "start" => 1000 * strtotime($ev->getFechainicio()->format('Y-m-d H:i:s')), "end" => 1000 * strtotime($ev->getFechafin()->format('Y-m-d H:i:s')));
         }
         $result = array("success" => 1, "result" => $jevents);
         $response = new JsonResponse();
         $response->setData($result);
         return $response;
     } else {
         $result = array("success" => 1, "result" => array());
         $response = new JsonResponse();
         $response->setData($result);
         return $response;
     }
 }
Exemplo n.º 16
0
 /**
  * Search for the specified entity by its property
  *
  * @Route("/choices/{class}/{property}", name="BluemesaCoreBundle_ajax_choices")
  *
  * @param  Request   $request
  * @param  string    $class     Entity class to search for
  * @param  string    $property  Property to lookup in search
  * @return Response
  * @throws InvalidArgumentException
  */
 public function choicesAction(Request $request, $class, $property)
 {
     $query = $request->query->get('query');
     $repository = $this->getDoctrine()->getRepository($class);
     if (!$repository instanceof EntityRepository) {
         throw new InvalidArgumentException();
     }
     $qb = $repository->createQueryBuilder('b');
     $terms = explode(" ", $query);
     foreach ($terms as $term) {
         $qb = $qb->andWhere("b." . $property . " like '%" . $term . "%'");
     }
     $found = $qb->getQuery()->getResult();
     $propertyPath = null !== $property ? new PropertyPath($property) : null;
     $propertyAccessor = PropertyAccess::createPropertyAccessor();
     $options = array();
     foreach ($found as $entity) {
         if (null !== $propertyPath) {
             $options[] = (string) $propertyAccessor->getValue($entity, $propertyPath);
         } else {
             $options[] = (string) $entity;
         }
     }
     $response = new JsonResponse();
     $response->setData($options);
     return $response;
 }
Exemplo n.º 17
0
 /**
  * @param string $content
  * @param int $status
  * @param array $headers
  * @return Response
  */
 function response_json($content, $status = Response::HTTP_OK, array $headers = [])
 {
     // We have to do a little trick and do not allow WHMCS to sent all it's content.
     $response = new JsonResponse($content, $status, $headers);
     $response->sendHeaders();
     die($response->getContent());
 }
Exemplo n.º 18
0
 /**
  * Get the slug of a string in AJAX
  * 
  * @param   $request    The request. String to slug must be sent in $request['toSlug'] 
  *
  * @return  $response   Response 
  */
 public function getSlugAction(Request $request)
 {
     if ($request->isXmlHttpRequest()) {
         if ($toSlug = $request->get('toSlug')) {
             $slug = $this->container->get('lch.seo.tools')->getSlug($toSlug);
             $em = $this->getDoctrine()->getManager();
             $currentSite = $request->getSession()->get('currentSite');
             if (class_exists('\\LCH\\CatalogBundle\\Entity\\' . $request->get('className'))) {
                 $entitySlug = $em->getRepository('LCHCatalogBundle:' . $request->get('className'))->findOneBySlug($slug);
             } elseif (class_exists('\\LCH\\ModuleBundle\\Entity\\' . $request->get('className'))) {
                 $entitySlug = $em->getRepository('LCHModuleBundle:' . $request->get('className'))->findOneBySlug($slug);
             } else {
                 throw new NotFoundHttpException("Class " . $request->get('className') . " no exists");
             }
             // if slug already exists
             $response = new JsonResponse();
             $id = $request->get('id') != "" ? $request->get('id') : "0";
             $url = $this->container->get('lch.seo.tools')->getFrontUrlRedirection($id, $slug, $request->get('className'));
             if ($entitySlug) {
                 if ($request->get('id') == $entitySlug->getId()) {
                     // If the slug comes from the same entity
                     $response->setData(array('slug' => $slug, 'message' => $this->container->get('translator')->trans('seo.form.url.infos') . " " . $url));
                 } else {
                     $response->setData(array('slug' => $slug, 'error' => $this->container->get('translator')->trans("app.slugexists")));
                 }
             } else {
                 $response->setData(array('slug' => $slug, 'message' => $this->container->get('translator')->trans('seo.form.url.infos') . " " . $url));
             }
             return $response;
         }
     }
 }
Exemplo n.º 19
0
 /**
  * @Route("/graphql")
  *
  * @throws ConfigurationException
  *
  * @return JsonResponse
  */
 public function defaultAction()
 {
     if ($this->get('request_stack')->getCurrentRequest()->getMethod() == 'OPTIONS') {
         return $this->createEmptyResponse();
     }
     list($query, $variables) = $this->getPayload();
     $schemaClass = $this->getParameter('graphql.schema_class');
     if (!$schemaClass || !class_exists($schemaClass)) {
         return new JsonResponse([['message' => 'Schema class ' . $schemaClass . ' does not exist']], 200, $this->getParameter('graphql.response.headers'));
     }
     if (!$this->get('service_container')->initialized('graphql.schema')) {
         $schema = new $schemaClass();
         if ($schema instanceof ContainerAwareInterface) {
             $schema->setContainer($this->get('service_container'));
         }
         $this->get('service_container')->set('graphql.schema', $schema);
     }
     /** @var Processor $processor */
     $processor = $this->get('graphql.processor');
     $processor->processPayload($query, $variables);
     $response = new JsonResponse($processor->getResponseData(), 200, $this->getParameter('graphql.response.headers'));
     if ($this->getParameter('graphql.response.json_pretty')) {
         $response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT);
     }
     return $response;
 }
Exemplo n.º 20
0
 protected function doKernelResponse(Request $request, Response $response)
 {
     if (!$response instanceof DataResponse) {
         return;
     }
     $routeName = $request->attributes->get('_route');
     $route = $this->routes->get($routeName);
     if (!$route) {
         return;
     }
     $acceptedFormat = $route->getOption(RouteOptions::ACCEPTED_FORMAT);
     if (!$acceptedFormat) {
         $response->setContent('');
         $response->setStatusCode(406);
     }
     if ($this->encoder->supportsEncoding($acceptedFormat) && $acceptedFormat === 'json') {
         $contentType = $request->getMimeType($acceptedFormat);
         $jsonResponse = new JsonResponse($response->getContent());
         $response->setContent($jsonResponse->getContent());
         $response->headers->set('Content-Type', $contentType);
     } elseif ($this->encoder->supportsEncoding($acceptedFormat)) {
         $contentType = $request->getMimeType($acceptedFormat);
         $content = $this->encoder->encode($response->getContent(), $acceptedFormat);
         $response->setContent($content);
         $response->headers->set('Content-Type', $contentType);
     }
 }
Exemplo n.º 21
0
 /**
  * Preparing a JsonResponse
  *
  * @param array $data
  * @param integer $statusCode
  */
 protected function prepareJsonResponse($data = array(), $statusCode = Response::HTTP_OK)
 {
     $response = new JsonResponse();
     $response->setData($data);
     $response->setStatusCode($statusCode);
     return $response;
 }
Exemplo n.º 22
0
 public function datePromotionsAction($hotelId, $dateStart)
 {
     $em = $this->getDoctrine()->getManager();
     $hotel = $em->getRepository('KvartiriBundle:Hotels')->find($hotelId);
     $test = '';
     if ($hotel) {
         $date = new \DateTime($dateStart);
         $now = new \DateTime();
         $diff = date_diff($date, $now);
         $daysDiff = $diff->y * 365.25 + $diff->m * 30 + $diff->d + $diff->h / 24 + $diff->i / 60;
         $checkValue = 0;
         $getPromotion = "";
         foreach ($hotel->getPromotionEarlyBooking() as $promotion) {
             $numbreDaysPromotionDB = $promotion->getDays();
             if ($numbreDaysPromotionDB && $daysDiff >= $numbreDaysPromotionDB && $checkValue < $numbreDaysPromotionDB) {
                 $checkValue = $numbreDaysPromotionDB;
                 $getPromotion = $promotion->getDiscount() * 100;
                 $getPromotion = "You have " . $getPromotion . "% discount";
             } else {
                 $getPromotion = "we can not offer you a promotion";
             }
         }
         //            $promotion = $date->diff($now)->format("%d days, %h hours and %i minuts");
     } else {
         $test = null;
     }
     //        return $this->render('UsersBundle:ClientsRequests:promotions.html.twig', array('getPromotion' => $getPromotion));
     $response = new JsonResponse();
     return $response->setData(array('getPromotion' => $getPromotion));
 }
Exemplo n.º 23
0
 public function menuAction()
 {
     $em = $this->getDoctrine()->getManager();
     $allRegionsCities = $em->getRepository('KvartiriBundle:Regions')->findAll();
     if ($allRegionsCities) {
         $data = array();
         $cpt = 0;
         foreach ($allRegionsCities as $regionCities) {
             $cpt1 = 0;
             $data[$cpt]['label'] = $regionCities->getName();
             $data[$cpt]['id'] = $regionCities->getId();
             $child = array();
             foreach ($regionCities->getCities() as $city) {
                 $child[$cpt1]['label'] = $city->getName();
                 $child[$cpt1]['id'] = $city->getId();
                 $cpt1++;
             }
             $data[$cpt]['children'] = $child;
             $cpt++;
         }
     } else {
         $data = null;
     }
     $response = new JsonResponse();
     return $response->setData(array('data' => $data));
 }
 public function onKernelView(GetResponseForControllerResultEvent $event)
 {
     if (!$event->isMasterRequest()) {
         return;
     }
     $request = $event->getRequest();
     if ('json' !== $request->getRequestFormat()) {
         return;
     }
     $result = $event->getControllerResult();
     if (null === $result) {
         $event->setResponse(new JsonResponse(null, 204));
         return;
     }
     if ($result instanceof Response) {
         return;
     }
     $response = new JsonResponse();
     if ($request->isMethod('POST')) {
         $response->setStatusCode(201);
     }
     if (!is_scalar($result)) {
         $result = $this->getSerializer()->normalize($result, null, ['groups' => $this->options['serialization_default_groups']]);
     }
     $response->setData($result);
     $event->setResponse($response);
 }
Exemplo n.º 25
0
 public function acceptCookiesAction($id)
 {
     $this->setCookie($id);
     $response = new JsonResponse();
     $response->setData(['message' => 'Cookiewall block added to session']);
     return $response;
 }
Exemplo n.º 26
0
 public function getJSONError($error)
 {
     $response = new JsonResponse();
     $data = array('success' => false, 'error' => $error);
     $response->setData($data);
     return $response;
 }
 /**
  * This listener is run when the KernelEvents::EXCEPTION event is triggered
  *
  * @param GetResponseForExceptionEvent $event
  * @return null
  */
 public function on_kernel_exception(GetResponseForExceptionEvent $event)
 {
     $exception = $event->getException();
     $message = $exception->getMessage();
     if ($exception instanceof \phpbb\exception\exception_interface) {
         $message = $this->language->lang_array($message, $exception->get_parameters());
     }
     if (!$event->getRequest()->isXmlHttpRequest()) {
         page_header($this->language->lang('INFORMATION'));
         $this->template->assign_vars(array('MESSAGE_TITLE' => $this->language->lang('INFORMATION'), 'MESSAGE_TEXT' => $message));
         $this->template->set_filenames(array('body' => 'message_body.html'));
         page_footer(true, false, false);
         $response = new Response($this->template->assign_display('body'), 500);
     } else {
         $data = array();
         if (!empty($message)) {
             $data['message'] = $message;
         }
         if (defined('DEBUG')) {
             $data['trace'] = $exception->getTrace();
         }
         $response = new JsonResponse($data, 500);
     }
     if ($exception instanceof HttpExceptionInterface) {
         $response->setStatusCode($exception->getStatusCode());
         $response->headers->add($exception->getHeaders());
     }
     $event->setResponse($response);
 }
 public function menuappAction()
 {
     $menuItems = $this->container->get('app_core.menu')->getMenu();
     $response = new JsonResponse();
     $json = $this->createResponse($menuItems);
     return $response->setData($json);
 }
 public function jsonAction()
 {
     $repository = $this->getDoctrine()->getRepository('AppTruckingBundle:Trucks');
     $result = $repository->getTrucksToJson();
     $response = new JsonResponse();
     return $response->setData($result);
 }
Exemplo n.º 30
0
 public function getHttpResponse()
 {
     $result = $this->getResponseArray();
     $response = new JsonResponse($result);
     $response->setEncodingOptions($response->getEncodingOptions() | JSON_UNESCAPED_UNICODE);
     return $response;
 }