本文整理汇总了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')));
}
示例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'));
}
示例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);
}
}
示例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;
}
示例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);
}
示例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;
}
示例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());
}
示例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;
}
示例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');
}
示例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));
}
}
示例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;
}
示例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));
}
示例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;
}
示例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);
}