setRequestFormat() public method

Sets the request format.
public setRequestFormat ( string $format )
$format string The request format
 /**
  * {@inheritdoc}
  */
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE)
 {
     if ($request->headers->has('Accept')) {
         $request->setRequestFormat($request->getFormat($request->headers->get('Accept')));
     }
     return $this->httpKernel->handle($request, $type, $catch);
 }
 /**
  * Just a modified Symfony\Bundle\TwigBundle\Controller\ExceptionController::findTemplate().
  * It will try to find an appropriate error template in the CoreBundle and will fallback to
  * the Twig default template if it can't find anything.
  *
  * @param Request $request
  * @param string  $format
  * @param int     $code          An HTTP response status code
  * @param bool    $showException
  *
  * @return string
  */
 protected function findTemplate(Request $request, $format, $code, $showException)
 {
     $name = $showException ? 'exception' : 'error';
     if ($showException && 'html' == $format) {
         $name = 'exception_full';
     }
     // For error pages, try to find a template for the specific HTTP status code and format
     if (!$showException) {
         // CampaignChain template?
         $template = sprintf('@CampaignChainCore/Exception/%s%s.%s.twig', $name, $code, $format);
         if ($this->templateExists($template)) {
             return $template;
         }
         // Fallback to default
         $template = sprintf('@Twig/Exception/%s%s.%s.twig', $name, $code, $format);
         if ($this->templateExists($template)) {
             return $template;
         }
     }
     // try to find a template for the given format
     // CampaignChain template?
     $template = sprintf('@CampaignChainCore/Exception/%s.%s.twig', $name, $code, $format);
     if ($this->templateExists($template)) {
         return $template;
     }
     // Fallback to default
     $template = sprintf('@Twig/Exception/%s.%s.twig', $name, $format);
     if ($this->templateExists($template)) {
         return $template;
     }
     // default to a generic HTML exception
     $request->setRequestFormat('html');
     return sprintf('@Twig/Exception/%s.html.twig', $showException ? 'exception_full' : $name);
 }
 /**
  * {@inheritdoc}
  */
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
 {
     foreach ($this->formats as $format => $mime_type) {
         $request->setFormat($format, $mime_type);
     }
     $request->setRequestFormat($this->negotiator->getContentType($request));
     return $this->app->handle($request, $type, $catch);
 }
Beispiel #4
0
 /** @test */
 public function it_sets_content_type_header_depending_on_request_format()
 {
     $response = $this->provideResponse();
     $request = new Request();
     $request->setRequestFormat('xml');
     $response->prepare($request);
     $this->assertSame('application/hal+xml', $response->headers->get('Content-Type'));
 }
 public function testFallbackWhenNotSupported()
 {
     $request = new Request();
     $request->setRequestFormat('html');
     $format = ErrorFormatGuesser::guessErrorFormat($request, ['xml' => ['text/xml'], 'jsonld' => ['application/ld+json', 'application/json']]);
     $this->assertEquals('xml', $format['key']);
     $this->assertEquals('text/xml', $format['value'][0]);
 }
 /**
  * @param Request $request
  */
 protected function setRequestFormat(Request $request)
 {
     $default = Format::getDefault();
     $format = $request->getRequestFormat($request->query->get('_format', $default));
     if (!in_array($format, $this->outputFormats)) {
         $format = $default;
     }
     $request->setRequestFormat($format);
 }
 /**
  * {@inheritdoc}
  */
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE)
 {
     $mapping = ['application/json' => 'json', 'application/hal+json' => 'hal_json', 'application/xml' => 'xml', 'text/html' => 'html'];
     $accept = $request->headers->get('Accept') ?: ['text/html'];
     if (isset($mapping[$accept[0]])) {
         $request->setRequestFormat($mapping[$accept[0]]);
     }
     return $this->app->handle($request, $type, $catch);
 }
 /**
  * @return Symfony\Component\HttpFoundation\Response
  */
 public function definitionAction(Request $request, $webservice)
 {
     $response = new Response($this->getWebServiceContext($webservice)->getWsdlFileContent($this->container->get('router')->generate('_webservice_call', array('webservice' => $webservice), UrlGeneratorInterface::ABSOLUTE_URL)));
     $query = $request->query;
     if ($query->has('wsdl') || $query->has('WSDL')) {
         $request->setRequestFormat('wsdl');
     }
     return $response;
 }
 public function testDoNothingWhenHtmlRequested()
 {
     $request = new Request([], [], ['_api_respond' => true]);
     $request->setRequestFormat('html');
     $eventProphecy = $this->prophesize(GetResponseForExceptionEvent::class);
     $eventProphecy->getRequest()->willReturn($request)->shouldBeCalled();
     $listener = new ExceptionListener('foo:bar');
     $listener->onKernelException($eventProphecy->reveal());
 }
Beispiel #10
0
 public function __invoke(Request $request, FlattenException $exception, $format)
 {
     $statusCode = $exception->getStatusCode();
     try {
         $template = $this->twig->resolveTemplate(['Exception/error' . $statusCode . '.' . $format . '.twig', 'Exception/error.' . $format . '.twig', 'Exception/error.html.twig']);
     } catch (\Twig_Error_Loader $e) {
         $request->setRequestFormat('html');
         $content = (new ExceptionHandler(false))->getHtml($exception);
         return new Response($content, $exception->getStatusCode(), $exception->getHeaders());
     }
     // We cannot find a template that matches the precise format so we will default
     // to html as previously in the ExceptionHandler
     if (substr($template->getTemplateName(), -9) == 'html.twig') {
         $request->setRequestFormat('html');
     }
     $variables = ['exception' => $exception, 'status_code' => $statusCode, 'status_text' => isset(Response::$statusTexts[$statusCode]) ? Response::$statusTexts[$statusCode] : ''];
     return new Response($template->render($variables), $statusCode);
 }
 public function getParameters()
 {
     $respondRequest = new Request([], [], ['_api_respond' => true]);
     $respondRequest->setRequestFormat('html');
     $resourceClassRequest = new Request([], [], ['_api_resource_class' => 'Foo']);
     $resourceClassRequest->setRequestFormat('html');
     $jsonRequest = new Request([], [], ['_api_resource_class' => 'Foo']);
     $jsonRequest->setRequestFormat('json');
     return [[$respondRequest, 'api_platform.swagger.action.ui'], [$resourceClassRequest, 'api_platform.swagger.action.ui'], [new Request(), null], [$jsonRequest, null]];
 }
 /**
  * {@inheritdoc}
  */
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE)
 {
     // Register available mime types.
     foreach ($this->formats as $format => $mime_type) {
         $request->setFormat($format, $mime_type);
     }
     // Determine the request format using the negotiator.
     $request->setRequestFormat($this->getContentType($request));
     return $this->app->handle($request, $type, $catch);
 }
Beispiel #13
0
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
 {
     if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
         $data = json_decode($request->getContent(), true);
         $request->request->replace(is_array($data) ? $data : []);
     }
     if (in_array('application/json', $request->getAcceptableContentTypes())) {
         $request->setRequestFormat('json');
     }
     return $response = $this->app->handle($request, $type, $catch);
 }
 public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
 {
     // IF an API URL, show the result as JSON - otherwise show HTML format
     $format = strncmp($request->getPathInfo(), '/api/', strlen('/api/')) == 0 ? 'json' : 'html';
     $request->setRequestFormat($format);
     $currentContent = $this->getAndCleanOutputBuffering($request->headers->get('X-Php-Ob-Level', -1));
     $showException = $request->attributes->get('showException', $this->debug);
     // As opposed to an additional parameter, this maintains BC
     $code = $exception->getStatusCode();
     return new Response($this->twig->render($this->findTemplate($request, $request->getRequestFormat(), $code, $showException), array('status_code' => $code, 'status_text' => isset(Response::$statusTexts[$code]) ? Response::$statusTexts[$code] : '', 'exception' => $exception, 'logger' => $logger, 'currentContent' => $currentContent)));
 }
 public function testOnKernelControllerNegotiationStopped()
 {
     $event = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Event\\GetResponseEvent')->disableOriginalConstructor()->getMock();
     $request = new Request();
     $request->setRequestFormat('xml');
     $event->expects($this->once())->method('getRequest')->will($this->returnValue($request));
     $formatNegotiator = new FormatNegotiator();
     $formatNegotiator->add(new RequestMatcher('/'), array('stop' => true));
     $formatNegotiator->add(new RequestMatcher('/'), array('fallback_format' => 'json'));
     $listener = new FormatListener($formatNegotiator);
     $listener->onKernelRequest($event);
     $this->assertEquals($request->getRequestFormat(), 'xml');
 }
 /**
  * @param Request $request
  * @param integer $code
  * @param string $format
  * @return string|null
  */
 protected function resolve(Request $request, $code, $format)
 {
     $loader = $this->app['twig.loader'];
     $templates = array('Exception/error' . $code . '.' . $format . '.twig', 'Exception/error.' . $format . '.twig', 'Exception/error.html.twig', '@Flint/Exception/error.' . $format . '.twig', '@Flint/Exception/error.html.twig');
     foreach ($templates as $template) {
         if (false == $loader->exists($template)) {
             continue;
         }
         if (strpos($template, '.html.twig')) {
             $request->setRequestFormat('html');
         }
         return $template;
     }
 }
 /**
  * Test FormatListener won't overwrite request format when it was already specified
  *
  * @dataProvider useSpecifiedFormatDataProvider
  */
 public function testUseSpecifiedFormat($format, $result)
 {
     $event = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Event\\GetResponseEvent')->disableOriginalConstructor()->getMock();
     $request = new Request();
     if ($format) {
         $request->setRequestFormat($format);
     }
     $event->expects($this->once())->method('getRequest')->will($this->returnValue($request));
     $formatNegotiator = $this->getMockBuilder('FOS\\RestBundle\\Util\\FormatNegotiator')->disableOriginalConstructor()->getMock();
     $formatNegotiator->expects($this->any())->method('getBestMediaType')->will($this->returnValue('application/xml'));
     $listener = new FormatListener($formatNegotiator);
     $listener->onKernelRequest($event);
     $this->assertEquals($request->getRequestFormat(), $result);
 }
Beispiel #18
0
 public function setBaseRequestFormat()
 {
     // Check headers for Accept
     $acceptHeaders = $this->request->getAcceptableContentTypes();
     foreach ($acceptHeaders as $header) {
         $baseFormt = $this->request->getFormat($header);
         if ($baseFormt == Format::FORMAT_JSON) {
             $this->request->setRequestFormat($baseFormt);
         }
         // Override base HTML format with JSON (default)
         if ($baseFormt == 'html') {
             $this->request->setRequestFormat(Format::FORMAT_JSON);
         }
     }
 }
 /**
  * @param string  $endpoint
  * @param Request $request
  * @return Response
  */
 public function routerAction($endpoint, Request $request)
 {
     $request->setRequestFormat($request->getContentType());
     if ($request->getMethod() !== Request::METHOD_POST) {
         throw new MethodNotAllowedHttpException(array(Request::METHOD_POST));
     }
     try {
         $endpoint = $this->endpointManager->getEndpoint($endpoint);
     } catch (\InvalidArgumentException $e) {
         throw new NotFoundHttpException('Not Found', $e);
     }
     try {
         return $endpoint->handleRequest($request);
     } catch (BadRequestException $e) {
         throw new BadRequestHttpException('Bad Request', $e);
     }
 }
 public function testCreate204Response()
 {
     $kernelProphecy = $this->prophesize(HttpKernelInterface::class);
     $request = new Request([], [], ['_api_respond' => true]);
     $request->setRequestFormat('xml');
     $request->setMethod(Request::METHOD_DELETE);
     $event = new GetResponseForControllerResultEvent($kernelProphecy->reveal(), $request, HttpKernelInterface::MASTER_REQUEST, 'foo');
     $listener = new RespondListener();
     $listener->onKernelView($event);
     $response = $event->getResponse();
     $this->assertEquals('foo', $response->getContent());
     $this->assertEquals(Response::HTTP_NO_CONTENT, $response->getStatusCode());
     $this->assertEquals('text/xml; charset=utf-8', $response->headers->get('Content-Type'));
     $this->assertEquals('Accept', $response->headers->get('Vary'));
     $this->assertEquals('nosniff', $response->headers->get('X-Content-Type-Options'));
     $this->assertEquals('deny', $response->headers->get('X-Frame-Options'));
 }
 public function testServiceDescriptionActionInJsonFormat()
 {
     /** @var UrlGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject $urlGenerator */
     $urlGenerator = $this->getMock('Symfony\\Component\\Routing\\Generator\\UrlGeneratorInterface', array('generate', 'setContext', 'getContext'));
     $urlGenerator->expects($this->once())->method('generate')->with($this->equalTo('tq_extdirect_router'), $this->equalTo(array('endpoint' => 'api')))->willReturn('http://example.com/api/router');
     /** @var \TQ\ExtDirect\Service\Endpoint|\PHPUnit_Framework_MockObject_MockObject $endpoint */
     $endpoint = $this->getMock('TQ\\ExtDirect\\Service\\Endpoint', array('getId', 'createServiceDescription'), array(), '', false);
     $endpoint->expects($this->once())->method('getId')->willReturn('api');
     $endpoint->expects($this->once())->method('createServiceDescription')->with($this->equalTo('http://example.com/api/router'), $this->equalTo('json'));
     /** @var \TQ\ExtDirect\Service\EndpointManager|\PHPUnit_Framework_MockObject_MockObject $endpointManager */
     $endpointManager = $this->getMock('TQ\\ExtDirect\\Service\\EndpointManager', array('getEndpoint'));
     $endpointManager->expects($this->once())->method('getEndpoint')->with($this->equalTo('api'))->willReturn($endpoint);
     $controller = new ApiController($endpointManager, $urlGenerator);
     $request = new Request();
     $request->setMethod(Request::METHOD_GET);
     $request->setRequestFormat('json');
     $controller->apiAction('api', $request);
 }
 /**
  * @covers ::filter
  */
 public function testFilter()
 {
     $route_filter = new RequestFormatRouteFilter();
     $route_without_format = new Route('/test');
     $route_with_format = $route = new Route('/test');
     $route_with_format->setRequirement('_format', 'json');
     $route_with_multiple_formats = $route = new Route('/test');
     $route_with_multiple_formats->setRequirement('_format', 'json|xml');
     $collection = new RouteCollection();
     $collection->add('test_0', $route_without_format);
     $collection->add('test_1', $route_with_format);
     $collection->add('test_2', $route_with_multiple_formats);
     $request = new Request();
     $request->setRequestFormat('xml');
     $collection = $route_filter->filter($collection, $request);
     $this->assertCount(2, $collection);
     $this->assertEquals(array_keys($collection->all())[0], 'test_2');
     $this->assertEquals(array_keys($collection->all())[1], 'test_0');
 }
 protected function findTemplate(Request $request, $format, $code, $debug)
 {
     $name = $debug ? 'exception' : 'error';
     if ($debug && 'html' == $format) {
         $name = 'exception_full';
     }
     // when not in debug, try to find a template for the specific HTTP status code and format
     if (!$debug) {
         $template = new TemplateReference('MaximCMSBundle', 'Exception', $name . $code, $format, 'twig');
         if ($this->templateExists($template)) {
             return $template;
         }
     }
     // try to find a template for the given format
     $template = new TemplateReference('MaximCMSBundle', 'Exception', $name, $format, 'twig');
     if ($this->templateExists($template)) {
         return $template;
     }
     // default to a generic HTML exception
     $request->setRequestFormat('html');
     return new TemplateReference('TwigBundle', 'Exception', $name, 'html', 'twig');
 }
Beispiel #24
0
 public function testGetRequestFormat()
 {
     $request = new Request();
     $this->assertEquals('html', $request->getRequestFormat());
     $request = new Request();
     $this->assertNull($request->getRequestFormat(null));
     $request = new Request();
     $this->assertNull($request->setRequestFormat('foo'));
     $this->assertEquals('foo', $request->getRequestFormat(null));
 }
Beispiel #25
0
 /**
  * Tests onRequest on a html request.
  */
 public function testOnRequestOnHtml()
 {
     $event = $this->getMockBuilder('\\Symfony\\Component\\HttpKernel\\Event\\KernelEvent')->disableOriginalConstructor()->getMock();
     $request = new Request();
     $request->setRequestFormat('html');
     $event->expects($this->any())->method('getRequest')->will($this->returnValue($request));
     $this->routeProvider->expects($this->once())->method('preLoadRoutes')->with(['test2']);
     $this->state->expects($this->once())->method('get')->with('routing.non_admin_routes')->will($this->returnValue(array('test2')));
     $this->preloader->onRequest($event);
 }
 /**
  * @dataProvider getFormatsDataProvider
  * @param array  $formats
  * @param string $format
  */
 public function testAuthenticationExceptionIsConvertedToAnAccessDeniedHttpExceptionForFormat(array $formats, $format)
 {
     $request = new Request();
     $request->setRequestFormat($format);
     $this->doTestAuthenticationExceptionIsConvertedToAnHttpExceptionForRequest($request, $formats);
 }
 /**
  * Finds the template for the given format and status code.
  *
  * Note this method needs to be overridden in case another
  * engine than Twig should be supported;
  *
  * This code is inspired by TwigBundle and should be synchronized on a regular basis
  * see src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php
  *
  * @param Request $request
  * @param string  $format
  * @param int     $statusCode
  * @param bool    $showException
  *
  * @return TemplateReference
  */
 protected function findTemplate(Request $request, $format, $statusCode, $showException)
 {
     $name = $showException ? 'exception' : 'error';
     if ($showException && 'html' == $format) {
         $name = 'exception_full';
     }
     // when not in debug, try to find a template for the specific HTTP status code and format
     if (!$showException) {
         $template = new TemplateReference('TwigBundle', 'Exception', $name . $statusCode, $format, 'twig');
         if ($this->container->get('templating')->exists($template)) {
             return $template;
         }
     }
     // try to find a template for the given format
     $template = new TemplateReference('TwigBundle', 'Exception', $name, $format, 'twig');
     if ($this->container->get('templating')->exists($template)) {
         return $template;
     }
     // default to a generic HTML exception
     $request->setRequestFormat('html');
     return new TemplateReference('TwigBundle', 'Exception', $showException ? 'exception_full' : $name, 'html', 'twig');
 }
 /**
  * @dataProvider serializerEnableMaxDepthChecksProvider
  */
 public function testSerializerEnableMaxDepthChecks($enableMaxDepthChecks, $expectedMaxDepth)
 {
     $this->createViewResponseListener(['json' => true]);
     $viewAnnotation = new ViewAnnotation([]);
     $viewAnnotation->setSerializerEnableMaxDepthChecks($enableMaxDepthChecks);
     $request = new Request();
     $request->setRequestFormat('json');
     $request->attributes->set('_view', $viewAnnotation);
     $this->templating->expects($this->any())->method('render')->will($this->returnValue('foo'));
     $view = new View();
     $event = $this->getResponseEvent($request, $view);
     $this->listener->onKernelView($event);
     $context = $view->getSerializationContext();
     $maxDepth = $context->getMaxDepth();
     $this->assertEquals($expectedMaxDepth, $maxDepth);
 }
Beispiel #29
0
 private function getPdfContent(PdfAnnotation $pdfAnnotation, Response $response, Request $request, $stylesheetContent)
 {
     try {
         $responseContent = $response->getContent();
         $pdfContent = null;
         if ($pdfAnnotation->enableCache) {
             $cacheKey = md5($responseContent . $stylesheetContent);
             if ($this->cache->test($cacheKey)) {
                 $pdfContent = $this->cache->load($cacheKey);
             }
         }
         if ($pdfContent === null) {
             $pdfFacade = $this->pdfFacadeBuilder->setDocumentParserType($pdfAnnotation->documentParserType)->build();
             $pdfContent = $pdfFacade->render($responseContent, $stylesheetContent);
             if ($pdfAnnotation->enableCache) {
                 $this->cache->save($pdfContent, $cacheKey);
             }
         }
         return $pdfContent;
     } catch (\Exception $e) {
         $request->setRequestFormat('html');
         $response->headers->set('content-type', 'text/html');
         throw $e;
     }
 }
 public function testAcceptHeaderTakePrecedenceOverRequestFormat()
 {
     $request = new Request([], [], ['_api_resource_class' => 'Foo']);
     $request->headers->set('Accept', 'application/json');
     $request->setRequestFormat('xml');
     $eventProphecy = $this->prophesize(GetResponseEvent::class);
     $eventProphecy->getRequest()->willReturn($request)->shouldBeCalled();
     $event = $eventProphecy->reveal();
     $listener = new AddFormatListener(new Negotiator(), ['xml' => ['application/xml'], 'json' => ['application/json']]);
     $listener->onKernelRequest($event);
     $this->assertSame('json', $request->getRequestFormat());
 }