本文整理汇总了PHP中Symfony\Component\HttpFoundation\Response::setStatusCode方法的典型用法代码示例。如果您正苦于以下问题:PHP Response::setStatusCode方法的具体用法?PHP Response::setStatusCode怎么用?PHP Response::setStatusCode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Symfony\Component\HttpFoundation\Response
的用法示例。
在下文中一共展示了Response::setStatusCode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: onKernelException
public function onKernelException(GetResponseForExceptionEvent $event)
{
if ('prod' == $this->kernel->getEnvironment()) {
// exception object
$exception = $event->getException();
$navService = $this->container->get('ssone.cms.navigation');
$logger = $this->container->get('logger');
$logger->error($exception->getMessage());
$host = $navService->host;
// new Response object
$response = new Response();
// set response content
$response->setContent($this->templating->render('SSoneCMSThemeBundle:' . $navService->domainTemplate, array('navigation' => $navService->templateNavigationMap, 'pageClass' => "notfound404", 'pageTitle' => "Not found 404", 'metaDescription' => $navService->metaDescription, 'content' => array("attributes" => array("template" => "404/" . $host . ".html.twig")), 'modules' => "", 'multiLanguageLinks' => "", 'exception' => $exception)));
// HttpExceptionInterface is a special type of exception
// that holds status code and header details
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
} else {
$response->setStatusCode(500);
}
// set the new $response object to the $event
$event->setResponse($response);
}
}
示例2: putCategoryAction
/**
* @View()
*/
public function putCategoryAction($id, Request $request)
{
$this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');
$em = $this->getDoctrine()->getManager();
$response = new Response();
$data = $request->request->all();
if ($id === "null") {
$category = new Category();
} else {
$category = $em->getRepository('AppBundle\\Entity\\Asset\\Category')->find($id);
}
$form = $this->createForm(CategoryType::class, $category, ['allow_extra_fields' => true]);
try {
$form->submit($data);
if ($form->isValid()) {
$category = $form->getData();
$em->persist($category);
$em->flush();
$response->setStatusCode($request->getMethod() === 'POST' ? 201 : 204);
$response->headers->set('Location', $this->generateUrl('app_admin_api_categories_get_category', array('id' => $category->getId()), true));
} else {
return $form;
}
} catch (Exception $e) {
$response->setStatusCode(400);
$response->setContent(json_encode(['message' => 'errors', 'errors' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
}
return $response;
}
示例3: invalidate
/**
* Handle invalidation, including Http PURGE requests.
* All non-allowed PURGE requests will receive an HTTP 405
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @param boolean $catch
*
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function invalidate( Request $request, $catch = false )
{
if ( $request->getMethod() !== 'PURGE' && $request->getMethod() !== 'BAN' )
{
return parent::invalidate( $request, $catch );
}
// Reject all non-authorized clients
if ( !$this->isInternalRequestAllowed( $request ) )
{
return new Response( '', 405 );
}
$response = new Response();
$store = $this->getStore();
if ( $store instanceof RequestAwarePurger )
{
$result = $store->purgeByRequest( $request );
}
else
{
$result = $store->purge( $request->getUri() );
}
if ( $result === true )
{
$response->setStatusCode( 200, 'Purged' );
}
else
{
$response->setStatusCode( 404, 'Not purged' );
}
return $response;
}
示例4: getResponse
/**
* Handle a request for a file
*
* @param Request $request HTTP request
* @return Response
*/
public function getResponse(Request $request)
{
$response = new Response();
$response->prepare($request);
$path = implode('/', $request->getUrlSegments());
if (!preg_match('~serve-file/e(\\d+)/l(\\d+)/d([ia])/c([01])/([a-zA-Z0-9\\-_]+)/(.*)$~', $path, $m)) {
return $response->setStatusCode(400)->setContent('Malformatted request URL');
}
list(, $expires, $last_updated, $disposition, $use_cookie, $mac, $path_from_dataroot) = $m;
if ($expires && $expires < time()) {
return $response->setStatusCode(403)->setContent('URL has expired');
}
$hmac_data = array('expires' => (int) $expires, 'last_updated' => (int) $last_updated, 'disposition' => $disposition, 'path' => $path_from_dataroot, 'use_cookie' => (int) $use_cookie);
if ((bool) $use_cookie) {
$hmac_data['cookie'] = $this->getCookieValue($request);
}
ksort($hmac_data);
$hmac = $this->crypto->getHmac($hmac_data);
if (!$hmac->matchesToken($mac)) {
return $response->setStatusCode(403)->setContent('HMAC mistmatch');
}
$dataroot = $this->config->getDataPath();
$filenameonfilestore = "{$dataroot}{$path_from_dataroot}";
if (!is_readable($filenameonfilestore)) {
return $response->setStatusCode(404)->setContent('File not found');
}
$actual_last_updated = filemtime($filenameonfilestore);
if ($actual_last_updated != $last_updated) {
return $response->setStatusCode(403)->setContent('URL has expired');
}
$if_none_match = $request->headers->get('if_none_match');
if (!empty($if_none_match)) {
// strip mod_deflate suffixes
$request->headers->set('if_none_match', str_replace('-gzip', '', $if_none_match));
}
$etag = '"' . $actual_last_updated . '"';
$response->setPublic()->setEtag($etag);
if ($response->isNotModified($request)) {
return $response;
}
$public = $use_cookie ? false : true;
$content_disposition = $disposition == 'i' ? 'inline' : 'attachment';
$headers = ['Content-Type' => (new MimeTypeDetector())->getType($filenameonfilestore)];
$response = new BinaryFileResponse($filenameonfilestore, 200, $headers, $public, $content_disposition);
$sendfile_type = $this->config->getVolatile('X-Sendfile-Type');
if ($sendfile_type) {
$request->headers->set('X-Sendfile-Type', $sendfile_type);
$mapping = (string) $this->config->getVolatile('X-Accel-Mapping');
$request->headers->set('X-Accel-Mapping', $mapping);
$response->trustXSendfileTypeHeader();
}
$response->prepare($request);
if (empty($expires)) {
$expires = strtotime('+1 year');
}
$expires_dt = (new DateTime())->setTimestamp($expires);
$response->setExpires($expires_dt);
$response->setEtag($etag);
return $response;
}
示例5: rpcAction
/**
* RPC url action
*
* @param $bundle
* @param $service
* @param $method
* @param Request $request
*
* @Route("/{bundle}/{service}/{method}" , defaults={"_format": "json"})
* @Method("POST")
*
* @return Response
*/
public function rpcAction($bundle, $service, $method, Request $request)
{
$response = new Response();
$translator = $this->get('translator');
try {
$prefix = 'Hazu.Service';
$serviceObject = $this->get("{$prefix}.{$bundle}.{$service}");
if (true === method_exists($serviceObject, $method)) {
$params = json_decode($request->getContent(), true);
if (null === $params) {
throw new \Exception('$params não é um JSON valido');
}
$rService = $serviceObject->{$method}($params);
} else {
throw new \Exception($translator->trans('Metodo não encontrado'));
}
} catch (ServiceNotFoundException $e) {
$rService = new HazuException($e->getMessage());
$response->setStatusCode(500);
} catch (\Exception $e) {
$rService = new HazuException($e->getMessage());
$response->setStatusCode(500);
} finally {
$serializer = SerializerBuilder::create()->build();
$rJson = $serializer->serialize($rService, 'json', SerializationContext::create()->enableMaxDepthChecks());
$response->headers->set('x-hazu-type', gettype($rService));
if (gettype($rService) == 'object') {
$response->headers->set('x-hazu-class', get_class($rService));
}
$response->setContent($rJson);
}
return $response;
}
示例6: getResponse
/**
* Handle a request for a file
*
* @param Request $request HTTP request
* @return Response
*/
public function getResponse($request)
{
$response = new Response();
$response->prepare($request);
$path = implode('/', $request->getUrlSegments());
if (!preg_match('~download-file/g(\\d+)$~', $path, $m)) {
return $response->setStatusCode(400)->setContent('Malformatted request URL');
}
$this->application->start();
$guid = (int) $m[1];
$file = get_entity($guid);
if (!$file instanceof ElggFile) {
return $response->setStatusCode(404)->setContent("File with guid {$guid} does not exist");
}
$filenameonfilestore = $file->getFilenameOnFilestore();
if (!is_readable($filenameonfilestore)) {
return $response->setStatusCode(404)->setContent('File not found');
}
$last_updated = filemtime($filenameonfilestore);
$etag = '"' . $last_updated . '"';
$response->setPublic()->setEtag($etag);
if ($response->isNotModified($request)) {
return $response;
}
$response = new BinaryFileResponse($filenameonfilestore, 200, array(), false, 'attachment');
$response->prepare($request);
$expires = strtotime('+1 year');
$expires_dt = (new DateTime())->setTimestamp($expires);
$response->setExpires($expires_dt);
$response->setEtag($etag);
return $response;
}
示例7: setStatus
/**
* Sets the given status code in the corresponding header.
*
* Note that headers are generally not overwritten!
*
* @param int $statusCode
*/
public function setStatus($statusCode)
{
if ($this->statusCode === null) {
$this->statusCode = $statusCode;
$this->response->setStatusCode($statusCode);
}
}
示例8: show
public function show()
{
$assetic = $this->getServices()->get($this->getServices()->getProperty('asseticServiceName', 'assetic'));
$response = new Response();
$response->setExpires(new \DateTime());
if (empty($this->asset) || strpos($this->asset, '/') === false) {
$response->setStatusCode(400);
return $response;
}
list(, $formulaName, ) = explode('/', $this->asset);
// asset not found
if (empty($formulaName) || !$assetic->getAssetManager()->has($formulaName)) {
$response->setStatusCode(404);
return $response;
}
$formula = $assetic->getAssetManager()->getFormula($formulaName);
if ($formula[0] instanceof AssetInterface) {
$asset = $formula[0];
} else {
$asset = $assetic->getFactory()->createAsset($formula[0], $formula[1], $formula[2]);
}
if (null !== ($lastModified = $asset->getLastModified())) {
$date = new \DateTime();
$date->setTimestamp($lastModified);
$response->setLastModified($date);
}
$formula['last_modified'] = $lastModified;
$response->setETag(md5($asset->getContent()));
$this->defineContentType($response);
if ($response->isNotModified($this->getContext()->getRequest())) {
return $response;
}
$response->setContent($this->cacheAsset($asset)->dump());
return $response;
}
示例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: chunk
/**
* Chunk the request into parts as
* desired by the request range header.
*
* @param Response $response
* @param FileInterface $file
*/
protected function chunk(Response $response, FileInterface $file)
{
$size = $chunkStart = $file->getSize();
$end = $chunkEnd = $size;
$response->headers->set('Content-length', $size);
$response->headers->set('Content-Range', "bytes 0-{$end}/{$size}");
if (!($range = array_get($_SERVER, 'HTTP_RANGE'))) {
return;
}
list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
if (strpos($range, ',') !== false) {
$response->setStatusCode(416, 'Requested Range Not Satisfiable');
$response->headers->set('Content-Range', "bytes 0-{$end}/{$size}");
}
if ($range == '-') {
$chunkStart = $size - substr($range, 1);
} else {
$range = explode('-', $range);
$chunkStart = $range[0];
$chunkEnd = isset($range[1]) && is_numeric($range[1]) ? $range[1] : $size;
}
$chunkEnd = $chunkEnd > $end ? $end : $chunkEnd;
if ($chunkStart > $chunkEnd || $chunkStart > $size || $chunkEnd >= $size) {
$response->setStatusCode(416, 'Requested Range Not Satisfiable');
$response->headers->set('Content-Range', "bytes 0-{$end}/{$size}");
}
}
示例11: onKernelException
/**
* Renders the defined {@see ExceptionListener::$errorTemplate}, which has been defined via YAML
* settings, on exception.
*
* Note, that the function is only called, if the *debug value* is set or *error pages* are
* enabled via Parameter *stvd.error_page.enabled*.
*
* @param GetResponseForExceptionEvent $event
*/
public function onKernelException(GetResponseForExceptionEvent $event)
{
// don't do anything if it's not the master request
if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
return;
}
// You get the exception object from the received event
$exception = $event->getException();
// Customize your response object to display the exception details
$response = new Response();
// set response content
$response->setContent($this->templating->render($this->errorTemplate, array('exception' => $exception)));
// HttpExceptionInterface is a special type of exception that
// holds status code and header details
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
} else {
// If the exception's status code is not valid, set it to *500*. If it's valid, the
// status code will be transferred to the response.
if ($exception->getCode()) {
$response->setStatusCode($exception->getCode());
} else {
$response->setStatusCode(500);
}
}
// Send the modified response object to the event
$event->setResponse($response);
}
示例12: onKernelException
public function onKernelException(GetResponseForExceptionEvent $event)
{
// You get the exception object from the received event
$exception = $event->getException();
if (!$exception instanceof ValidationException) {
return;
}
// Customize your response object to display the exception details
$response = new Response();
$validationErrors = $exception->getErrorList();
$errorArray = array();
foreach ($validationErrors as $error) {
$errorArray[$error->getPropertyPath()] = $error->getMessage();
}
//TODO permettre de paramétrer le format de renvoi des erreurs
$errorMessage = json_encode($errorArray);
//$this->serializer->serialize($validationErrors, 'json');
$response->setContent($errorMessage);
// HttpExceptionInterface is a special type of exception that
// holds status code and header details
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
} else {
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
}
// Send the modified response object to the event
$event->setResponse($response);
}
示例13: 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;
}
}
示例14: 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;
}
示例15: testFullRedirectNotProducedInDevEnv
public function testFullRedirectNotProducedInDevEnv()
{
$listener = $this->getListener(true);
$this->response->headers->add(array('location' => self::TEST_URL));
$this->response->setStatusCode(503);
$this->templating->expects($this->never())->method('renderResponse');
$this->event->expects($this->once())->method('setResponse');
$listener->onResponse($this->event);
}