当前位置: 首页>>代码示例>>PHP>>正文


PHP Request::getRequestFormat方法代码示例

本文整理汇总了PHP中Symfony\Component\HttpFoundation\Request::getRequestFormat方法的典型用法代码示例。如果您正苦于以下问题:PHP Request::getRequestFormat方法的具体用法?PHP Request::getRequestFormat怎么用?PHP Request::getRequestFormat使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Symfony\Component\HttpFoundation\Request的用法示例。


在下文中一共展示了Request::getRequestFormat方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1:

 function it_checks_if_its_a_html_request(Request $request)
 {
     $request->getRequestFormat()->willReturn('html');
     $this->isHtmlRequest()->shouldReturn(true);
     $request->getRequestFormat()->willReturn('json');
     $this->isHtmlRequest()->shouldReturn(false);
 }
开发者ID:ahmadrabie,项目名称:Sylius,代码行数:7,代码来源:RequestConfigurationSpec.php

示例2: createFeed

 /**
  * @param $data array
  * @param format string, either rss or atom
  */
 protected function createFeed(View $view, Request $request)
 {
     $feed = new Feed();
     $data = $view->getData();
     $item = current($data);
     $annotationData = $this->reader->read($item);
     if ($item && ($feedData = $annotationData->getFeed())) {
         $class = get_class($item);
         $feed->setTitle($feedData->getName());
         $feed->setDescription($feedData->getDescription());
         $feed->setLink($this->urlGen->generateCollectionUrl($class));
         $feed->setFeedLink($this->urlGen->generateCollectionUrl($class, $request->getRequestFormat()), $request->getRequestFormat());
     } else {
         $feed->setTitle('Camdram feed');
         $feed->setDescription('Camdram feed');
     }
     $lastModified = null;
     $accessor = PropertyAccess::createPropertyAccessor();
     // Add one or more entries. Note that entries must be manually added once created.
     foreach ($data as $document) {
         $entry = $feed->createEntry();
         $entry->setTitle($accessor->getValue($document, $feedData->getTitleField()));
         $entry->setLink($this->urlGen->generateUrl($document));
         $entry->setDescription($this->twig->render($feedData->getTemplate(), array('entity' => $document)));
         if ($accessor->isReadable($document, $feedData->getUpdatedAtField())) {
             $entry->setDateModified($accessor->getValue($document, $feedData->getUpdatedAtField()));
         }
         $feed->addEntry($entry);
         if (!$lastModified || $entry->getDateModified() > $lastModified) {
             $lastModified = $entry->getDateModified();
         }
     }
     $feed->setDateModified($lastModified);
     return $feed->export($request->getRequestFormat());
 }
开发者ID:dstansby,项目名称:camdram,代码行数:39,代码来源:FeedViewHandler.php

示例3: searchAction

 /**
  * @Route("/search.{_format}", name="search",
  *      requirements={"_format": "|rss|atom"},
  *      defaults={"_format": "html"}
  * )
  * @Method({"GET"})
  * @Template("ChaosTangentFansubEbooksAppBundle:Search:index.html.twig")
  */
 public function searchAction(Request $request)
 {
     $page = $request->query->get('page', 1);
     $query = $request->query->get('q', null);
     $seriesResults = [];
     $lineResults = [];
     $lineResultsSerialized = '';
     $searchTime = 0;
     if (!empty(trim($query))) {
         $start = microtime(true);
         $om = $this->get('doctrine')->getManager();
         $lineRepo = $om->getRepository('Entity:Line');
         $lineResults = $lineRepo->search($query, $page, 30);
         if ($page == 1) {
             $seriesRepo = $om->getRepository('Entity:Series');
             $seriesResults = $seriesRepo->search($query);
         }
         $searchTime = microtime(true) - $start;
         $searchEvent = new SearchEvent($query, $page, $searchTime);
         $this->get('event_dispatcher')->dispatch(SearchEvents::SEARCH, $searchEvent);
         $serializer = $this->get('jms_serializer');
         $context = $this->get('fansubebooks.serializer.context');
         $lineResultsSerialized = $serializer->serialize($lineResults->getResults(), 'json', $context);
     }
     $viewData = ['query' => $query, 'series_results' => $seriesResults, 'line_results' => $lineResults, 'line_results_serialized' => $lineResultsSerialized, 'search_time' => $searchTime];
     if ($request->getRequestFormat() == 'rss') {
         return $this->render('ChaosTangentFansubEbooksAppBundle:Search:index.rss.twig', $viewData);
     } else {
         if ($request->getRequestFormat() == 'atom') {
             return $this->render('ChaosTangentFansubEbooksAppBundle:Search:index.atom.twig', $viewData);
         }
     }
     return $viewData;
 }
开发者ID:johnnoel,项目名称:fansubebooks.chaostangent.com,代码行数:42,代码来源:SearchController.php

示例4: format

 /**
  * Returns different responses dependening on the request format.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The request
  *
  * @return \Symfony\Component\HttpFoundation\Response
  *   The response.
  */
 public function format(Request $request)
 {
     switch ($request->getRequestFormat()) {
         case 'json':
             return new JsonResponse(['some' => 'data']);
         case 'xml':
             return new Response('<xml></xml>', Response::HTTP_OK, ['Content-Type' => 'application/xml']);
         default:
             return new Response($request->getRequestFormat());
     }
 }
开发者ID:ddrozdik,项目名称:dmaps,代码行数:20,代码来源:TestController.php

示例5: serializeRawData

 /**
  * Tries to serialize data that are not API resources (e.g. the entrypoint or data returned by a custom controller).
  *
  * @param GetResponseForControllerResultEvent $event
  * @param Request                             $request
  * @param object                              $controllerResult
  *
  * @throws RuntimeException
  */
 private function serializeRawData(GetResponseForControllerResultEvent $event, Request $request, $controllerResult)
 {
     if (!$request->attributes->get('_api_respond')) {
         return;
     }
     if (is_object($controllerResult)) {
         $event->setControllerResult($this->serializer->serialize($controllerResult, $request->getRequestFormat()));
         return;
     }
     if (!$this->serializer instanceof EncoderInterface) {
         throw new RuntimeException(sprintf('The serializer instance must implements the "%s" interface.', EncoderInterface::class));
     }
     $event->setControllerResult($this->serializer->encode($controllerResult, $request->getRequestFormat()));
 }
开发者ID:api-platform,项目名称:core,代码行数:23,代码来源:SerializeListener.php

示例6: uploadAction

 /**
  * @Route("/upload", name="picture_create", defaults={"_format": "html"})
  */
 public function uploadAction(Request $request)
 {
     $format = $request->getRequestFormat();
     $em = $this->getDoctrine()->getManager();
     $picture = new Picture();
     $form = $this->createForm(PictureType::class, $picture);
     if ($request->isMethod('POST')) {
         $form->handleRequest($request);
         if ($form->isSubmitted()) {
             if ($form->isValid()) {
                 $picture->setUser($this->get('security.token_storage')->getToken()->getUser());
                 $em->persist($picture);
                 $em->flush();
                 if ($request->isXmlHttpRequest()) {
                     $lReturn = array();
                     //use renderview instead of render, because renderview returns the rendered template
                     $pictureArray = array('id' => $picture->getId());
                     $lReturn['picture'] = $pictureArray;
                     $lReturn['rendered'] = $this->renderView('pictures/_singlePictureCard.html.twig', array('picture' => $picture));
                     return new Response(json_encode($lReturn), 200, array('Content-Type' => 'application/json'));
                 }
                 return $this->redirectToRoute('homepage');
             }
             if ($request->isXmlHttpRequest()) {
                 return $this->render('pictures/_pictureForm.html.twig', array('pictureForm' => $form->createView()), new Response(null, 422));
             }
             return $this->render('pictures/create.html.twig', array('pictureForm' => $form->createView()));
         }
     }
     if ($request->isXmlHttpRequest()) {
         return $this->render('pictures/_pictureForm.html.twig', array('pictureForm' => $form->createView()));
     }
     return $this->render('pictures/create.html.twig', array('pictureForm' => $form->createView()));
 }
开发者ID:VladoMS,项目名称:symfogram,代码行数:37,代码来源:PicturesConrollerController.php

示例7: prepare

 /**
  * 요청 포멧이 html 이 아닐 경우 redirect 하지 않고 데이터 형식으로 결과 출력
  *
  * @param Request $request request
  * @return mixed
  */
 public function prepare(Request $request)
 {
     if ($request->getRequestFormat() === 'json') {
         return new JsonResponse(array_merge($this->data, ['links' => ['rel' => 'self', 'href' => $this->targetUrl]]));
     }
     return parent::prepare($request);
 }
开发者ID:xpressengine,项目名称:xpressengine,代码行数:13,代码来源:RedirectResponse.php

示例8: guessTemplateName

 public function guessTemplateName(Request $request, $engine = 'twig')
 {
     if (!($namespace = $request->attributes->get('_controller'))) {
         throw new \InvalidArgumentException('Invalid Request Object');
     }
     list($controller, $action) = explode('::', $namespace);
     if (!preg_match('/Controller\\\\(.+)Controller$/', $controller, $matchController)) {
         throw new \InvalidArgumentException(sprintf('The "%s" class does not look like a controller class (it must be in a "Controller" sub-namespace and the class name must end with "Controller")', $controller));
     }
     if (!preg_match('/^(.+)Action$/', $action, $matchAction)) {
         throw new \InvalidArgumentException(sprintf('The "%s" method does not look like an action method (it does not end with Action)', $action));
     }
     if ($bundle = $this->getBundleForClass($controller)) {
         while ($bundleName = $bundle->getName()) {
             if (null === ($parentBundleName = $bundle->getParent())) {
                 $bundleName = $bundle->getName();
                 break;
             }
             $bundles = $this->kernel->getBundle($parentBundleName, false);
             $bundle = array_pop($bundles);
         }
     } else {
         $bundleName = null;
     }
     return new TemplateReference($bundleName, $matchController[1], $matchAction[1], $request->getRequestFormat(), $engine);
 }
开发者ID:timy-life,项目名称:segments,代码行数:26,代码来源:SymfonyTemplateGuesser.php

示例9: listAction

 public function listAction(Request $request, $sort)
 {
     $format = $request->getRequestFormat();
     if (!array_key_exists($sort, $this->sortFields)) {
         $msg = sprintf('%s is not a valid sorting field', $sort);
         if ('json' === $format) {
             return new JsonResponse(array('status' => 'error', 'message' => $msg), 406);
         }
         throw new HttpException($msg, 406);
     }
     $sortField = $this->sortFields[$sort];
     $query = $this->getRepository('Developer')->queryAllWithBundlesSortedBy($sortField);
     $paginator = $this->getPaginator($query, $request->query->get('page', 1), $request->query->get('limit', 18));
     if ('json' === $format) {
         $result = array('results' => array(), 'total' => $paginator->getNbResults());
         /* @var $developer Developer */
         foreach ($paginator as $developer) {
             $result['results'][] = array('name' => $developer->getName(), 'email' => $developer->getEmail(), 'avatarUrl' => $developer->getAvatarUrl(), 'fullName' => $developer->getFullName(), 'company' => $developer->getCompany(), 'location' => $developer->getLocation(), 'blog' => $developer->getUrl(), 'lastCommitAt' => $developer->getLastCommitAt() ? $developer->getLastCommitAt()->getTimestamp() : null, 'score' => $developer->getScore(), 'url' => $this->generateUrl('developer_show', array('name' => $developer->getName()), true));
         }
         if ($paginator->hasPreviousPage()) {
             $result['prev'] = $this->generateUrl('developer_list', array('sort' => $sort, 'page' => $paginator->getPreviousPage(), 'limit' => $request->query->get('limit'), '_format' => 'json'), true);
         }
         if ($paginator->hasNextPage()) {
             $result['next'] = $this->generateUrl('developer_list', array('sort' => $sort, 'page' => $paginator->getNextPage(), 'limit' => $request->query->get('limit'), '_format' => 'json'), true);
         }
         return new JsonResponse($result);
     }
     $this->highlightMenu('developers');
     return $this->render('KnpBundlesBundle:Developer:list.html.twig', array('developers' => $paginator, 'sort' => $sort, 'sortLegends' => $this->sortLegends));
 }
开发者ID:KnpLabs,项目名称:KnpBundles,代码行数:30,代码来源:DeveloperController.php

示例10: 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;
 }
开发者ID:studiocaramia,项目名称:redking_OAuthBundle,代码行数:33,代码来源:FacebookController.php

示例11: collect

 /**
  * {@inheritdoc}
  */
 public function collect(Request $request, Response $response, \Exception $exception = null)
 {
     $responseHeaders = $response->headers->all();
     $cookies = array();
     foreach ($response->headers->getCookies() as $cookie) {
         $cookies[] = $this->getCookieHeader($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
     }
     if (count($cookies) > 0) {
         $responseHeaders['Set-Cookie'] = $cookies;
     }
     $attributes = array();
     foreach ($request->attributes->all() as $key => $value) {
         if (is_object($value)) {
             $attributes[$key] = sprintf('Object(%s)', get_class($value));
             if (is_callable(array($value, '__toString'))) {
                 $attributes[$key] .= sprintf(' = %s', (string) $value);
             }
         } else {
             $attributes[$key] = $value;
         }
     }
     $content = null;
     try {
         $content = $request->getContent();
     } catch (\LogicException $e) {
         // the user already got the request content as a resource
         $content = false;
     }
     $this->data = array('format' => $request->getRequestFormat(), 'content' => $content, 'content_type' => $response->headers->get('Content-Type') ? $response->headers->get('Content-Type') : 'text/html', 'status_code' => $response->getStatusCode(), 'request_query' => $request->query->all(), 'request_request' => $request->request->all(), 'request_headers' => $request->headers->all(), 'request_server' => $request->server->all(), 'request_cookies' => $request->cookies->all(), 'request_attributes' => $attributes, 'response_headers' => $responseHeaders, 'session_attributes' => $request->hasSession() ? $request->getSession()->all() : array(), 'path_info' => $request->getPathInfo());
 }
开发者ID:netcon-source,项目名称:prontotype,代码行数:33,代码来源:RequestDataCollector.php

示例12: needConsoleInjection

 public function needConsoleInjection(Request $request, Response $response)
 {
     if ($request->isXmlHttpRequest() || !$response->headers->has('X-Debug-Token') || '3' === substr($response->getStatusCode(), 0, 1) || $response->headers->has('Content-Type') && false === strpos($response->headers->get('Content-Type'), 'html') || 'html' !== $request->getRequestFormat()) {
         return false;
     }
     return true;
 }
开发者ID:rdalambic,项目名称:web-crystal-palace,代码行数:7,代码来源:ToolbarListener.php

示例13: indexAction

 /**
  * Render the provided content.
  *
  * When using the publish workflow, enable the publish_workflow.request_listener
  * of the core bundle to have the contentDocument as well as the route
  * checked for being published.
  * We don't need an explicit check in this method.
  *
  * @param Request $request
  * @param object  $contentDocument
  * @param string  $contentTemplate Symfony path of the template to render
  *                                 the content document. If omitted, the
  *                                 default template is used.
  *
  * @return Response
  */
 public function indexAction(Request $request, $contentDocument, $contentTemplate = null)
 {
     $contentTemplate = $contentTemplate ?: $this->defaultTemplate;
     $contentTemplate = str_replace(array('{_format}', '{_locale}'), array($request->getRequestFormat(), $request->getLocale()), $contentTemplate);
     $params = $this->getParams($request, $contentDocument);
     return $this->renderResponse($contentTemplate, $params);
 }
开发者ID:kea,项目名称:PUGXCmfPageBundle,代码行数:23,代码来源:GenericController.php

示例14: collect

    /**
     * {@inheritdoc}
     */
    public function collect(Request $request, Response $response, \Exception $exception = null)
    {
        $responseHeaders = $response->headers->all();
        $cookies = array();
        foreach ($response->headers->getCookies() as $cookie) {
            $cookies[] = $this->getCookieHeader($cookie->getName(), $cookie->getValue(), $cookie->getExpire(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
        }
        if (count($cookies) > 0) {
            $responseHeaders['Set-Cookie'] = $cookies;
        }

        $attributes = array();
        foreach ($request->attributes->all() as $key => $value) {
            $attributes[$key] = is_object($value) ? sprintf('Object(%s)', get_class($value)) : $value;
        }

        $this->data = array(
            'format'             => $request->getRequestFormat(),
            'content_type'       => $response->headers->get('Content-Type') ? $response->headers->get('Content-Type') : 'text/html',
            'status_code'        => $response->getStatusCode(),
            'request_query'      => $request->query->all(),
            'request_request'    => $request->request->all(),
            'request_headers'    => $request->headers->all(),
            'request_server'     => $request->server->all(),
            'request_cookies'    => $request->cookies->all(),
            'request_attributes' => $attributes,
            'response_headers'   => $responseHeaders,
            'session_attributes' => $request->hasSession() ? $request->getSession()->getAttributes() : array(),
        );
    }
开发者ID:Gregwar,项目名称:symfony,代码行数:33,代码来源:RequestDataCollector.php

示例15: onLogoutSuccess

 /**
  * Creates a Response object to send upon a successful logout.
  *
  * @param Request $request
  *
  * @return Response never null
  */
 public function onLogoutSuccess(Request $request)
 {
     if ($request->isXmlHttpRequest() or 'json' == $request->getRequestFormat()) {
         return new JsonResponse(true);
     }
     return new RedirectResponse($this->router->generate('homepage'));
 }
开发者ID:blab2015,项目名称:seh,代码行数:14,代码来源:AuthenticationHandler.php


注:本文中的Symfony\Component\HttpFoundation\Request::getRequestFormat方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。