本文整理汇总了PHP中Symfony\Component\HttpFoundation\Response::setContent方法的典型用法代码示例。如果您正苦于以下问题:PHP Response::setContent方法的具体用法?PHP Response::setContent怎么用?PHP Response::setContent使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Symfony\Component\HttpFoundation\Response
的用法示例。
在下文中一共展示了Response::setContent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: edit
public function edit(Request $request, Response $response, array $args)
{
$template = new \App\Template('form.twig');
$template->title = 'Create';
// Date granularities.
$sql = "SELECT id, title FROM date_granularities ORDER BY id ASC";
$template->date_granularities = $this->db->query($sql)->fetchAll();
// Item.
$item = new Item();
if (isset($args['id'])) {
$template->title = 'Editing #' . $args['id'];
$item = new Item($args['id']);
}
$template->item = $item;
// User.
$item->setUser($this->user);
if (!$this->user->getId()) {
$msg = 'You have to ' . ' <a href="' . $this->config->baseUrl() . '/login" class="alert-link">log in</a> ' . ' before you can add or edit items.';
$template->alert('info', $msg);
$response->setContent($template->render());
return $response;
}
$template->groups = $this->user->getGroups();
// Other template data.
$template->fileContents = $item->getFileContents();
$template->itemTags = $item->getTagsString();
$template->itemReadGroupId = $item->getReadGroup()->id;
$template->itemEditGroupId = $item->getEditGroup()->id;
$response->setContent($template->render());
return $response;
}
示例2: editAction
/**
* @Route("/edit/{user}",name="registration_admin_edit")
*/
public function editAction(Request $request, $user)
{
$response = new Response();
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(EditType::class);
$form->handleRequest($request);
$user = $em->getRepository(RegUser::class)->findOneByUsername($user);
if ($form->isValid()) {
$data = $form->getData();
if ($data['action'] === true) {
$password = new Password();
$password->setHash($user->getPasswordHash());
$password->setId('default');
$password->setEncoder(CryptEncoder::class);
$userLdap = $this->get('cloud.ldap.util.usermanipulator')->createUserObject($user->getUsername(), $password);
$userLdap->setAltEmail($user->getAltEmail());
$userLdap->setGpgPublicKey($user->getGpgPublicKey());
$this->get('cloud.ldap.util.usermanipulator')->create($userLdap);
$em->remove($user);
} elseif ($data['action'] === false) {
$em->remove($user);
} else {
$response->setStatusCode(400);
return $response;
}
$em->flush();
} else {
$response->setContent(json_encode(['successfully' => false, 'error' => $form->getErrors(true)->__toString()]));
return $response;
}
$response->setContent(json_encode(['successfully' => true]));
return $response;
}
示例3: saveImagenAction
public function saveImagenAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$response = new Response();
try {
$image = $request->get("image");
if (!$image) {
$response->setContent(json_decode(array("error" => ">No hay imagen seleccionada.")));
$response->setStatusCode(Response::HTTP_NOT_FOUND);
return $response;
}
$user = $this->getUser();
$user->setPicture($image);
$em->persist($user);
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'Se actualizo la imagen de perfil');
$response->setContent(json_encode(array("success" => "Imagen actualizada.")));
$response->setStatusCode(Response::HTTP_OK);
return $response;
} catch (\Exception $exc) {
$response->setContent(json_encode(array("error" => "Error al intentar guardar la imagen, intente con una mas pequeña o acerque mas la imagen")));
$response->setStatusCode(Response::HTTP_NOT_FOUND);
return $response;
}
}
示例4: _injectDatatableScript
/**
* Injects the datatable scripts into the given HTTP Response.
*
* @param Response $response A Response instance
*/
protected function _injectDatatableScript(Response $response, Request $request)
{
$content = $response->getContent();
$pos_body = strripos($content, '</body>');
if (!$pos_body) {
return;
}
$session = $request->getSession();
$dom = '<script id="alidatatable-scripts" type="text/javascript">';
$pos_container = strripos($content, 'alidatatable-scripts');
$sess_dta = $session->get('datatable');
$dta_script = null;
array_walk($sess_dta, function (&$part, &$key) {
$part = trim(preg_replace('/\\s\\s+/', ' ', $part));
});
$dta_script = implode("\n", $sess_dta);
$session->set('datatable', array());
if (!$pos_container) {
$dta_container = $dom;
$content = substr_replace($content, $dta_container . '</script>', $pos_body, 0);
$response->setContent($content);
}
$pos_dta = strripos($content, $dom);
$content = substr_replace($content, $dta_script, $pos_dta + strlen($dom), 0);
$response->setContent($content);
}
示例5: getResponse
/**
* @param Request $request
*
* @return Response
*/
public static function getResponse(Request $request)
{
ignore_user_abort(true);
//turn off gzip compression
if (function_exists('apache_setenv')) {
apache_setenv('no-gzip', 1);
}
ini_set('zlib.output_compression', 0);
$response = new Response();
//removing any content encoding like gzip etc.
$response->headers->set('Content-Encoding', 'none');
//check to ses if request is a POST
if ($request->getMethod() == 'GET') {
$response->headers->set('Connection', 'close');
//return 1x1 pixel transparent gif
$response->headers->set('Content-Type', 'image/gif');
//avoid cache time on browser side
$response->headers->set('Content-Length', '42');
$response->headers->set('Cache-Control', 'private, no-cache, no-cache=Set-Cookie, proxy-revalidate');
$response->headers->set('Expires', 'Wed, 11 Jan 2000 12:59:00 GMT');
$response->headers->set('Last-Modified', 'Wed, 11 Jan 2006 12:59:00 GMT');
$response->headers->set('Pragma', 'no-cache');
$response->setContent(self::getImage());
} else {
$response->setContent(' ');
}
return $response;
}
示例6: getSubscriptionAction
/**
* Get callback response from paywall/payment provider and proccess it.
*
* @Route("/paywall/subscriptions/get", name="paywall_subscribe", options={"expose"=true})
*/
public function getSubscriptionAction(Request $request)
{
$subscriptionService = $this->container->get('paywall.subscription.service');
$userService = $this->get('user');
$translator = $this->get('translator');
$user = $userService->getCurrentUser();
$em = $this->get('em');
$response = new Response();
$response->headers->set('Content-Type', 'text/html');
$response->setCharset('utf-8');
$templatesService = $this->get('newscoop.templates.service');
$chosenSubscription = $em->getRepository('Newscoop\\PaywallBundle\\Entity\\Subscriptions')->findOneByName($request->get('subscription_name'));
if (!$chosenSubscription) {
$response->setContent($templatesService->fetchTemplate("_paywall/error.tpl", array('msg' => $translator->trans('paywall.alert.notexists'))));
return $response;
}
$userSubscriptionInactive = $subscriptionService->getOneByUserAndSubscription($user->getId(), $chosenSubscription->getId(), 'N');
$userSubscription = $subscriptionService->getOneByUserAndSubscription($user->getId(), $chosenSubscription->getId());
if ($userSubscription || $userSubscriptionInactive) {
$response->setContent($templatesService->fetchTemplate("_paywall/error.tpl", array('msg' => $translator->trans('paywall.manage.error.exists.subscription'))));
return $response;
}
$specificationArray = $chosenSubscription->getSpecification()->toArray();
$specification = $specificationArray[0];
$subscription = $subscriptionService->create();
$subscriptionData = new SubscriptionData(array('userId' => $user, 'subscriptionId' => $chosenSubscription, 'publicationId' => $request->get('publication_id') ?: $specification->getPublication()->getId(), 'toPay' => $chosenSubscription->getPrice(), 'days' => $chosenSubscription->getRange(), 'currency' => $chosenSubscription->getCurrency(), 'type' => 'T', 'active' => false), $subscription);
$subscription = $subscriptionService->update($subscription, $subscriptionData);
$subscriptionService->save($subscription);
$this->dispatchNotificationEvent(PaywallEvents::ORDER_SUBSCRIPTION, $subscription);
$response->setContent($templatesService->fetchTemplate("_paywall/success.tpl", array('subscription' => $subscription)));
return $response;
}
示例7: getDatosCosteoAction
/**
* Obtener los datos del costeo
* @Get("/rest-service/costos/data/{codigo}", options={"expose"=true})
* @Rest\View
*/
public function getDatosCosteoAction($codigo)
{
$response = new Response();
// crea una respuesta con una cabecera ETag y Last-Modified
// para determinar si se debe calcular el indicador u obtener de la caché
// para el modo de desarrollo (dev) nunca tomar de caché
//$response->setETag($fichaTec->getId().'_datos');
//$response->setLastModified(($this->get('kernel')->getEnvironment() == 'dev') ? new \DateTime('NOW') : $fichaTec->getUltimaLectura() );
$response->setPublic();
// verifica que la respuesta no se ha modificado para la petición dada
//if ($response->isNotModified($this->getRequest())) {
// devuelve inmediatamente la respuesta 304 de la caché
// return $response;
//} else {
$resp = array();
$em = $this->getDoctrine()->getManager();
$data = $em->getRepository('CostosBundle:Formulario')->getDatosCosteo($codigo);
if (count($data) == 0) {
$response->setContent('{"estado" : "error", "msj": "' . $this->get('translator')->trans('_no_datos_') . '"}');
} else {
$response->setContent(json_encode($data));
}
return $response;
//}
}
示例8: doKernelResponse
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);
}
}
示例9: createAction
public function createAction()
{
$response = new Response();
$response->headers->set('Content-type', 'application/json');
if ($this->get('session')->get('user') === null) {
$response->setStatusCode(401);
$response->setContent(json_encode(array('response' => Response::$statusTexts[401])));
return $response;
}
$data = $this->getRequest()->request->all();
if (empty($data)) {
$data = json_decode($this->getRequest()->getContent(), true);
}
$this->handleUpload($data);
$userRepo = $this->getDoctrine()->getRepository('Emicro\\Bundles\\CoreBundle\\Entity\\User');
$canvasRepo = $this->getDoctrine()->getRepository('Emicro\\Bundles\\CoreBundle\\Entity\\Canvas');
$user = $this->get('session')->get('user');
$canvasRepo->setUser($userRepo->find($user->getId()));
if (isset($data['id'])) {
$canvas = $canvasRepo->update($data, $data['id']);
$response->setStatusCode(200);
} else {
$canvas = $canvasRepo->insert($data);
$response->setStatusCode(201);
}
$serializer = new JsonSerializer();
$response->setContent($serializer->serialize($canvas));
return $response;
}
示例10: testPlainRequest
public function testPlainRequest()
{
$testBody = 'test';
$this->response->setContent($testBody);
$this->listener->onResponse($this->event);
$this->assertEquals($testBody, $this->response->getContent());
}
示例11: createFileResponse
/**
* @param Request $request
* @param $storageKey
*
* @return Response
*/
protected function createFileResponse(Request $request, $storageKey)
{
$response = new Response();
$parts = explode('/', $storageKey);
$file = $this->getFile($parts[0]);
if (!$file) {
return $response->setContent('File not found.')->setStatusCode(Response::HTTP_NOT_FOUND);
}
if ($request->get('dl') !== null) {
$filename = $file->getFilename();
if (count($parts) > 1) {
$filename = $parts[count($parts) - 1];
}
$filenameFallback = filter_var($filename, FILTER_SANITIZE_URL);
if ($filenameFallback != $filename) {
$guesser = ExtensionGuesser::getInstance();
$extension = filter_var($guesser->guess($file->getMimeType()) ?: $file->getExtension(), FILTER_SANITIZE_URL);
$filenameFallback = $file->getStorageKey() . ($extension ? '.' . $extension : '');
}
$response->headers->set('Content-Disposition', $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename, $filenameFallback));
} else {
$response->setCache(array('etag' => $file->getStorageKey(), 'last_modified' => $file->getCreatedAt()));
if ($response->isNotModified($request)) {
return $response;
}
}
$response->setContent($file->getContents());
$response->headers->set('Content-type', $file->getMimeType());
$response->headers->set('Content-length', $file->getSize());
return $response;
}
示例12: handleResponse
/**
* Returns response based on request content type
* @param Request $request [description]
* @param [type] $response_data [description]
* @param integer $response_code [description]
* @return [type] [description]
*/
protected function handleResponse(Request $request, $response_data, $response_code = 200)
{
$response = new Response();
$contentType = $request->headers->get('Content-Type');
$format = null === $contentType ? $request->getRequestFormat() : $request->getFormat($contentType);
if ($format == 'json') {
$serializer = $this->get('serializer');
$serialization_context = SerializationContext::create()->enableMaxDepthChecks()->setGroups(array('Default', 'detail', 'from_user', 'from_oauth'));
$response->setContent($serializer->serialize($response_data, 'json', $serialization_context));
$response->headers->set('Content-Type', 'application/json');
} else {
if (is_array($response_data)) {
if (isset($response_data['message'])) {
$response->setContent($response_data['message']);
} else {
$response->setContent(json_encode($response_data));
}
}
}
if ($response_code == 0) {
$response->setStatusCode(500);
} else {
$response->setStatusCode($response_code);
}
return $response;
}
示例13: handleResponse
/**
* Returns Response in JSON Format, given value has to be some encodeable Stuff (most likely an array ;) )
* @param $value
* @return \Symfony\Component\HttpFoundation\Response
*/
public function handleResponse($value)
{
$this->throwNotFound($value);
$this->response->setStatusCode(200);
$this->response->setContent(json_encode($value));
$this->response->headers->set('Content-Type', 'application/json');
return $this->response;
}
示例14: pricesAction
/**
* Product prices lookup.
*
* @Route("/prices")
* @Method({"GET"})
* @Template()
*
* @param Request $request
* @return Response
*/
public function pricesAction(Request $request)
{
$pricesData = $this->getProductPrices();
$pricesDataJson = json_encode($pricesData);
// Formulate JSON response
$this->response->headers->set('Content-Type', 'application/json');
$this->response->setContent($pricesDataJson);
return $this->response;
}
示例15: show
public function show($params)
{
$slug = $params['slug'];
try {
$data['content'] = $this->pageReader->readBySlug($slug);
} catch (PageNotFoundException $e) {
$this->response->setStatusCode(404);
return $this->response->setContent('404 - Page not found');
}
$html = $this->twig->render('page.twig', $data);
return $this->response->setContent($html);
}