當前位置: 首頁>>代碼示例>>PHP>>正文


PHP Serializer::serialize方法代碼示例

本文整理匯總了PHP中Symfony\Component\Serializer\Serializer::serialize方法的典型用法代碼示例。如果您正苦於以下問題:PHP Serializer::serialize方法的具體用法?PHP Serializer::serialize怎麽用?PHP Serializer::serialize使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在Symfony\Component\Serializer\Serializer的用法示例。


在下文中一共展示了Serializer::serialize方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的PHP代碼示例。

示例1: get

 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')));
 }
開發者ID:haus23,項目名稱:haus23-api,代碼行數:27,代碼來源:QueryResourceController.php

示例2: accountAction

 /**
  * @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'));
 }
開發者ID:AlexanderTheGr,項目名稱:alexander,代碼行數:13,代碼來源:DefaultController.php

示例3: onKernelResponse

 /**
  * @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);
     }
 }
開發者ID:yapro,項目名稱:test-gallery.local,代碼行數:13,代碼來源:ViewListener.php

示例4: getFormExportCode

  /**
   * @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;
  }
開發者ID:AshishNaik021,項目名稱:iimisac-d8,代碼行數:15,代碼來源:Serializer.php

示例5: getResponse

 /**
  * @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);
 }
開發者ID:vardius,項目名稱:crud-bundle,代碼行數:14,代碼來源:ResponseHandler.php

示例6: generateResponse

 /**
  * 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;
 }
開發者ID:mcdir,項目名稱:SonatraFormExtensionsBundle,代碼行數:37,代碼來源:AjaxChoiceListHelper.php

示例7: newAction

 /**
  * 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());
 }
開發者ID:alexseif,項目名稱:miniERP,代碼行數:34,代碼來源:ProductsController.php

示例8: getResponse

 /**
  * 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;
 }
開發者ID:robinvliz,項目名稱:DatatablesBundle,代碼行數:36,代碼來源:DatatableQuery.php

示例9: getSerialize

 /**
  * @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');
 }
開發者ID:Futrille,項目名稱:iglesys,代碼行數:11,代碼來源:IglesysGeneralBundle.php

示例10: updateAction

 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'));
 }
開發者ID:Nipuna-Sankalpa,項目名稱:sasip_student_online_management_system,代碼行數:33,代碼來源:ExamConfigController.php

示例11: getAction

 /**
  *
  * @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));
     }
 }
開發者ID:RaquelDiazG,項目名稱:EjemploSymfony,代碼行數:22,代碼來源:ProductoController.php

示例12: checkTest

 /**
  * 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;
 }
開發者ID:michalgraczyk,項目名稱:calculus,代碼行數:49,代碼來源:TestsController.php

示例13: showAction

 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));
 }
開發者ID:dev-learning,項目名稱:webshop,代碼行數:7,代碼來源:ProductController.php

示例14: serialize

 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;
 }
開發者ID:RAFnut,項目名稱:Competition-REFU.G,代碼行數:8,代碼來源:UserController.php

示例15: setEventResponse

 /**
  * 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);
 }
開發者ID:eigentor,項目名稱:tommiblog,代碼行數:16,代碼來源:DefaultExceptionSubscriber.php


注:本文中的Symfony\Component\Serializer\Serializer::serialize方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。