function get(Request $req) { $resourceName = $req->get('resource'); if (!isset($this->module["resourceEntityMappings"][$resourceName])) { throw new NotFoundHttpException(); } $entityClass = $this->module["namespace"] . $this->module["resourceEntityMappings"][$resourceName]; // Filterer entities queried? if ($req->getQueryString() != null) { $querystring = $req->getQueryString(); $criteria = array(); $queryParts = \explode('&', $querystring); foreach ($queryParts as $queryPart) { $key_value = \explode('=', $queryPart); $criteria[$key_value[0]] = urldecode($key_value[1]); } $entities = $this->em->getRepository($entityClass)->findBy($criteria); // Single entity queried? } elseif ($req->get('id') != null) { $id = $req->get('id'); $entity = $this->em->getRepository($entityClass)->find($id); $entities = array($entity); } else { $entities = $this->em->getRepository($entityClass)->findAll(); } return new Response($this->serializer->serialize(array($resourceName => $entities), 'json'), 200, array('Content-Type' => $req->getMimeType('json'))); }
/** * @Route("/account/{url}/{appkey}") * */ public function accountAction($url, $appkey) { $encoder = new JsonEncoder(); $normalizer = new GetSetMethodNormalizer(); $serializer = new Serializer(array($normalizer), array($encoder)); $account = $this->getDoctrine()->getRepository('AdminBundle:Account')->findByUrl($url); $serializer->serialize($account, 'json'); return new Response($serializer->serialize($account, 'json'), 200, array('Content-Type' => 'application/json')); }
/** * @param GetResponseForControllerResultEvent $event */ public function onKernelResponse(GetResponseForControllerResultEvent $event) { $request = $event->getRequest(); if ($request->isXmlHttpRequest() && ($result = $event->getControllerResult()) && !empty($result['pagination']) && $result['pagination'] instanceof SlidingPagination) { $result = array('items' => $result['pagination']->getItems(), 'pagination' => $result['pagination']->getPaginationData(), 'paginationHtml' => $this->paginationExtension->render($this->twig, $result['pagination'])); $json = $this->serializer->serialize($result, 'json'); $response = new Response($json, Response::HTTP_OK, ['Content-Type' => 'application/json']); $event->setResponse($response); } }
/** * @param $fillpdf_form * @return string */ public function getFormExportCode(FillPdfFormInterface $fillpdf_form) { $fields = $this->entityHelper->getFormFields($fillpdf_form); $form_config = [ 'form' => $this->serializer->normalize($fillpdf_form), 'fields' => $this->serializer->normalize($fields), ]; $code = $this->serializer->serialize($form_config, 'json'); return $code; }
/** * @inheritDoc */ public function getResponse(string $format, string $view, string $templateName, $params, int $status = 200, array $headers = [], array $context = []) : Response { if ($format === 'html') { $response = $this->getHtml($view, $templateName, $params); } elseif ($this->serializer instanceof Serializer) { $response = $this->serializer->serialize($params, $format, $context); } else { throw new \Exception('The serializer service is not available by default. To turn it on, activate it in your project configuration.'); } return new Response($response, $status, $headers); }
/** * Generates the ajax response. * * @param Request $request The request * @param AjaxChoiceLoaderInterface|FormBuilderInterface|FormInterface $choiceLoader The choice loader or form or array * @param string $format The output format * @param string $prefix The prefix of parameters * * @return Response * * @throws InvalidArgumentException When the format is not allowed */ public static function generateResponse(Request $request, $choiceLoader, $format = 'json', $prefix = '') { $formats = array('xml', 'json'); if (!in_array($format, $formats)) { $msg = "The '%s' format is not allowed. Try with '%s'"; throw new InvalidArgumentException(sprintf($msg, $format, implode("', '", $formats))); } if ($choiceLoader instanceof FormBuilderInterface || $choiceLoader instanceof FormInterface) { $formatter = static::extractAjaxFormatter($choiceLoader); $choiceLoader = static::extractChoiceLoader($choiceLoader); } else { $formatter = static::createChoiceListFormatter(); } if (!$choiceLoader instanceof AjaxChoiceLoaderInterface) { throw new UnexpectedTypeException($choiceLoader, 'Sonatra\\Bundle\\FormExtensionsBundle\\Form\\ChoiceList\\Loader\\AjaxChoiceLoaderInterface'); } $data = static::getData($request, $choiceLoader, $formatter, $prefix); $encoders = array(new XmlEncoder(), new JsonEncoder()); $normalizers = array(new GetSetMethodNormalizer()); $serializer = new Serializer($normalizers, $encoders); $response = new Response(); $response->headers->set('Content-Type', 'application/' . $format); $response->setContent($serializer->serialize($data, $format)); return $response; }
/** * Displays a form to create a new Products product. * * @Security("has_role('ROLE_ACCOUNTANT')") * @Route("/new", name="products_new") * @Method({"GET", "POST"}) * @Template() */ public function newAction(Request $request) { $product = new Products(); $product->setEnabled(true); $form = $this->createCreateForm($product); $form->handleRequest($request); if ($form->isSubmitted()) { if ($form->isValid()) { $encoders = array(new XmlEncoder(), new JsonEncoder()); $normalizers = array(new ObjectNormalizer()); $serializer = new Serializer($normalizers, $encoders); $product->setRequiredDocuments($serializer->serialize($product->getRequiredDocuments(), 'json')); $pricing = $product->getPricing(); foreach ($pricing as $price) { if (empty($price->getId())) { $product->addPricing($price); } } $em = $this->getDoctrine()->getManager(); $em->persist($product); $em->flush(); return $this->redirect($this->generateUrl('products_show', array('id' => $product->getId()))); } } return array('product' => $product, 'product_form' => $form->createView()); }
/** * Get response. * * @param bool $buildQuery * * @return Response * @throws Exception */ public function getResponse($buildQuery = true) { false === $buildQuery ?: $this->buildQuery(); $fresults = new Paginator($this->execute(), true); $fresults->setUseOutputWalkers(false); $output = array('data' => array()); foreach ($fresults as $item) { if (is_callable($this->lineFormatter)) { $callable = $this->lineFormatter; $item = call_user_func($callable, $item); } foreach ($this->columns as $column) { $column->renderContent($item, $this); /** @var ActionColumn $column */ if ('action' === $column->getAlias()) { $column->checkVisibility($item); } } $output['data'][] = $item; } $outputHeader = array('draw' => (int) $this->requestParams['draw'], 'recordsTotal' => (int) $this->getCountAllResults($this->rootEntityIdentifier), 'recordsFiltered' => (int) $this->getCountFilteredResults($this->rootEntityIdentifier, $buildQuery)); $fullOutput = array_merge($outputHeader, $output); $fullOutput = $this->applyResponseCallbacks($fullOutput); $json = $this->serializer->serialize($fullOutput, 'json'); $response = new Response($json); $response->headers->set('Content-Type', 'application/json'); return $response; }
/** * @param $object * @return mixed */ public function getSerialize($object) { $encoders = array(new XmlEncoder(), new JsonEncoder()); $normalizers = array(new ObjectNormalizer()); $serializer = new Serializer($normalizers, $encoders); return $serializer->serialize($object, 'json'); }
public function updateAction(Request $request) { $ExamId = $request->get('id'); $em = $this->getDoctrine()->getManager(); $exam = $em->getRepository('ClassUserBundle:Exams')->find($ExamId); //under this condition edit form will filled with the existing data //when class being selected this mehtod will be invoked. if ($request->getMethod() == 'GET' && $exam != null) { $encoders = array(new JsonEncoder()); $normalizers = array(new ObjectNormalizer()); $serializer = new Serializer($normalizers, $encoders); $jsonContent = $serializer->serialize($exam, 'json'); return new \Symfony\Component\HttpFoundation\Response($jsonContent); } //this conditon will work when data being submitted through the form if ($request->getMethod() == 'POST' && $exam != null) { if ($request->request->get('fees')) { $exam->setFees($request->request->get('fees')); } if ($request->request->get('conductDay')) { $exam->setConductDay($request->request->get('conductDay')); } if ($request->request->get('time')) { $exam->setTime($request->request->get('time')); } if ($request->request->get('teacher_id')) { $exam->setTeacherid($request->request->get('teacher_id')); } $em->flush(); return new JsonResponse(array('message' => 'Updated Successfully')); } return new JsonResponse(array('message' => 'ERROR')); }
/** * * @param type $id Id del producto * @param type $format Formato de la salida * @return Response */ public function getAction($id, $format) { $producto = $this->getDoctrine()->getRepository('MiwDemoBundle:Producto')->find(intval($id)); $encoders = array(new XmlEncoder(), new JsonEncoder()); $normalizers = array(new ObjectNormalizer()); $serializer = new Serializer($normalizers, $encoders); if ($format == 'json') { $jsonContent = $serializer->serialize($producto, $format); return new Response($jsonContent); } elseif ($format == 'xml') { $xmlContent = $serializer->serialize($producto, $format); return new Response($xmlContent); } else { return $this->render("MiwDemoBundle:Producto:producto.html.twig", array("producto" => $producto)); } }
/** * Method checks test * * <p> * Steps * <ul> * <li>Step 1. Get user's answers from Request</li> * <li>Step 2. Create TestChecker and prepare tasks list based on user's answers (Step 1)</li> * <li>Step 3. Get correct answers for chosen tasks (tasks list from Step 2)</li> * <li>Step 4. Prepare array from Step 3 to comparing</li> * <li>Step 5. Get result by comparing user answers with array from Step 4</li> * </ul> * </p> * * @param \Symfony\Component\HttpFoundation\Request $request * @return \Symfony\Component\HttpFoundation\JsonResponse * * @Route("/Test/Weryfikacja" , name="test_check") * @Method({"POST"}) */ public function checkTest(Request $request) { $params = json_decode($request->getContent(), true); $test_checker = $this->get("test.checker"); // User answers [ task12 => B, task1 => E .... ]) $user_answers = !empty($params['user_answers']) ? $params['user_answers'] : array(); // Gets id property from sygnature $tasks_id_list = $test_checker->prepareTasksIdList($user_answers); // Gets tasks correct answers $answers = $this->getAnswers($tasks_id_list); // Creates table with [TASK_SYGNATURE => POINTS] $tasks_answers = $test_checker->prepareTestAnswers($answers); // Gets test results like FULL POINTS, USER POINTS, NEGATIVE POINTS and ARRAY WITH ANSWERS $result = $test_checker->compareAnswers($user_answers, $tasks_answers); // Check if user is logged and add points to his account $checker = $this->get('security.authorization_checker'); if ($checker->isGranted('IS_AUTHENTICATED_FULLY') && $checker->isGranted('ROLE_USER') && $result->getUserPoints() > 0) { $profile = $this->get('security.token_storage')->getToken()->getUser()->getProfile(); $profile->addPoints($result->getUserPoints()); $em = $this->getDoctrine()->getManager(); $em->persist($profile); $em->flush(); } $jsonContent = $this->serializer->serialize($result, 'json'); $response = new Response(); $response->setContent($jsonContent); $response->headers->set('Content-Type', 'application/json'); return $response; }
public function showAction() { $serializer = new Serializer([new ObjectNormalizer()], [new JsonEncode()]); $data = $this->productService->getAll(); $jsonData = $serializer->serialize($data, 'json'); return $this->templateEngine->renderResponse('AppBundle:admin:productList.html.twig', array('products' => $jsonData)); }
private function serialize($object) { $encoders = array(new XmlEncoder(), new JsonEncoder()); $normalizers = array(new ObjectNormalizer()); $serializer = new Serializer($normalizers, $encoders); $jsonContent = $serializer->serialize($object, 'json'); return $jsonContent; }
/** * Sets the Response for the exception event. * * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event * The current exception event. * @param int $status * The HTTP status code to set for the response. */ protected function setEventResponse(GetResponseForExceptionEvent $event, $status) { $format = $event->getRequest()->getRequestFormat(); $content = ['message' => $event->getException()->getMessage()]; $encoded_content = $this->serializer->serialize($content, $format); $response = new Response($encoded_content, $status); $event->setResponse($response); }
/** * Serialize an object to json. * * @todo There is an issue while serializing the Country object in JSON. * The country has the Country object (name and code) instead to have the country name. * * @param BatchGeocoded $object The BatchGeocoded object to serialize. * * @return string The serialized object in json. */ protected function serialize($object) { $serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]); $serialized = $serializer->serialize($object, 'json'); // transform to array to fix the serialization issue $serialized = json_decode($serialized, true); return json_encode($this->fixSerialization($serialized)); }
public function output($object) { $encoders = array(new XmlEncoder(), new JsonEncoder()); $normalizers = array(new ObjectNormalizer()); $serializer = new Serializer($normalizers, $encoders); $jsonContent = $serializer->serialize($object->getItems(), 'json'); echo $jsonContent; }
public function getAction() { $normalizer = new ObjectNormalizer(new ClassMetadataFactory(new YamlFileLoader(CONFIG_PATH . 'test_entity.yml')), new CamelCaseToSnakeCaseNameConverter()); $serializer = new Serializer([$normalizer], [new JsonEncoder(), new XmlEncoder()]); $test = new TestEntity(); $test->setMessage('Test'); $test = $serializer->deserialize('<test><id>1</id></test>', 'DG\\SymfonyCert\\Entity\\TestEntity', 'xml', ['object_to_populate' => $test]); return new Response($serializer->serialize($test, 'xml', ['groups' => ['group2']]), 200, ['Content-Type' => 'text/xml']); }
/** * Response constructor. * * @param string $content * @param int $status * @param array $headers */ public function __construct($content = '', $status = 200, $headers = array()) { $encoders = [new XmlEncoder()]; $normalizers = [new GetSetMethodNormalizer()]; $serializer = new Serializer($normalizers, $encoders); $contents_xml = $serializer->serialize($content, 'xml'); $headers['Content-Type'] = 'application/xml'; parent::__construct($contents_xml, $status = 200, $headers); }
public function userDataAction() { $user = $this->get('security.context')->getToken()->getUser(); $normalizer = new GetSetMethodNormalizer(); $normalizer->setIgnoredAttributes(array('password', 'roles', 'salt')); $serializer = new Serializer(array($normalizer), array(new JsonEncoder())); $json = $serializer->serialize($user, 'json'); return new Response($json); }
/** * Get results. * * @return \Symfony\Component\HttpFoundation\Response */ public function getSearchResults() { $this->buildQuery(); $this->executeQuery(); $json = $this->serializer->serialize($this->response, 'json'); $response = new Response($json); $response->headers->set('Content-Type', 'application/json'); return $response; }
/** * returns the xml sitemap * @return string sitemap in xml format */ public function __toString() { // Missing attribute xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" in urlset node $encoders = array(new XmlEncoder('urlset')); // anyway to use setIgnoredAttributes() dynamicly on each Url object? $normalizers = array(new GetSetMethodNormalizer()); $serializer = new Serializer($normalizers, $encoders); return (string) $serializer->serialize(array('url' => $this->urls), 'xml'); }
public function toJson() { $encoders = array(new XmlEncoder(), new JsonEncoder()); $normalizers = array(new ObjectNormalizer()); $serializer = new Serializer($normalizers, $encoders); $data['result'] = array(); $data['result'] = json_decode($serializer->serialize($this, 'json'), true); return json_encode($data); }
public function computeData($grid) { $xmlEncoder = new XmlEncoder(); $xmlEncoder->setRootNodeName('grid'); $serializer = new Serializer(array(new GetSetMethodNormalizer()), array('xml' => $xmlEncoder)); $data = $this->getGridData($grid); $convertData['titles'] = $data['titles']; $convertData['rows']['row'] = $data['rows']; $this->content = $serializer->serialize($convertData, 'xml'); }
/** * @Route("/gestion-empresarial/desarrollo-empresarial/comite-concursos/gestion/{idComite}", name="Comite") */ public function ComiteAction($idComite) { $em = $this->getDoctrine()->getManager(); $comite = $em->getRepository('AppBundle:Comite')->findOneBy(array('id' => $idComite)); //$elementos = $query->getResult(); $encoders = array(new XmlEncoder(), new JsonEncoder()); $normalizers = array(new GetSetMethodNormalizer()); $serializer = new Serializer($normalizers, $encoders); return new Response('{"": ' . $serializer->serialize($comite, 'json') . '}'); }
/** * @return array|Response */ public function render() { $encoders = array(new XmlEncoder()); $normalizers = array(new GetSetMethodNormalizer()); $serializer = new Serializer($normalizers, $encoders); $data = $serializer->serialize($this->data, $this->header); $response = new Response($data); $response->headers->set('Content-Type', 'text/xml'); return $response; }
/** * Creates mpi request formatted in xml * * @param string $storeId * @param string $key * @param \Namshi\Innovate\Payment\Transaction $transaction * @param \Namshi\Innovate\Payment\Card $card */ public function createMpiBody($storeId, $key, Transaction $transaction, Card $card) { $this->xmlBody = array(); $this->addStoreId($storeId); $this->addKey($key); $this->addTransaction($transaction); $this->addCard($card); $encoder = new XmlEncoder('remote'); $serializer = new Serializer(array(new GetSetMethodNormalizer()), array($encoder)); $this->setBody($serializer->serialize($this->xmlBody, 'xml')); }
public function getResponse($buildQuery = true) { false === $buildQuery ?: $this->buildQuery(); $fresults = new Paginator($this->execute(), true); $fresults->setUseOutputWalkers(false); $output = array('data' => array()); foreach ($fresults as $item) { // Line formatter if (is_callable($this->lineFormatter)) { $callable = $this->lineFormatter; $item = call_user_func($callable, $item); } // Images foreach ($this->columns as $column) { $data = $column->getDql(); /** @var ImageColumn $column */ if ('image' === $column->getAlias()) { if (true === $this->imagineBundle) { $item[$data] = $this->renderImage($item[$data], $column); } else { $item[$data] = $this->twig->render('SgDatatablesBundle:Helper:render_image.html.twig', array('image_name' => $item[$data], 'path' => $column->getRelativePath())); } } /** @var GalleryColumn $column */ if ('gallery' === $column->getAlias()) { $fields = explode('.', $data); if (true === $this->imagineBundle) { $galleryImages = ''; $counter = 0; $images = count($item[$fields[0]]); if (0 === $images) { $item[$fields[0]] = $this->renderImage(null, $column); } else { foreach ($item[$fields[0]] as $image) { $galleryImages = $galleryImages . $this->renderImage($image[$fields[1]], $column); if (++$counter == $column->getViewLimit()) { break; } } $item[$fields[0]] = $galleryImages; } } else { throw new InvalidArgumentException('getResponse(): Bundle "LiipImagineBundle" does not exist or it is not enabled.'); } } } $output['data'][] = $item; } $outputHeader = array('draw' => (int) $this->requestParams['draw'], 'recordsTotal' => (int) $this->getCountAllResults($this->rootEntityIdentifier), 'recordsFiltered' => (int) $this->getCountFilteredResults($this->rootEntityIdentifier)); $json = $this->serializer->serialize(array_merge($outputHeader, $output), 'json'); $response = new Response($json); $response->headers->set('Content-Type', 'application/json'); return $response; }
/** * Send an invalid UUID to trigger the entity validation. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity we want to check that was inserted correctly. * @param string $entity_type * The type of the entity that should be created. * @param array $context * Options normalizers/encoders have access to. */ public function assertCreateEntityInvalidSerialized(EntityInterface $entity, $entity_type, array $context = array()) { // Add a UUID that is too long. $entity->set('uuid', $this->randomMachineName(129)); $invalid_serialized = $this->serializer->serialize($entity, $this->defaultFormat, $context); $response = $this->httpRequest('entity/' . $entity_type, 'POST', $invalid_serialized, $this->defaultMimeType); // Unprocessable Entity as response. $this->assertResponse(422); // Verify that the text of the response is correct. $error = Json::decode($response); $this->assertEqual($error['error'], "Unprocessable Entity: validation failed.\nuuid.0.value: <em class=\"placeholder\">UUID</em>: may not be longer than 128 characters.\n"); }
public final function personSerialize($data, $format, array $contest = array()) { if ($format == 'text') { $json = parent::serialize($data, 'json'); $tablica = json_decode($json, true); foreach ($tablica as $key => $val) { echo $key . ":" . $val . '<br/>'; } } else { return parent::serialize($data, $format, $contest); } }