php Symfony-Component-HttpFoundation-AcceptHeader类(方法)实例源码

下面列出了php Symfony-Component-HttpFoundation-AcceptHeader 类(方法)源码代码实例,从而了解它的用法。

作者:webburz    项目:sylius-location-bundl   
/**
  * @param Request $request
  *
  * @throws ServiceCircularReferenceException When a circular reference is detected
  * @throws ServiceNotFoundException          When the service is not defined
  *
  * @return JsonResponse|Response
  */
 public function searchAction(Request $request)
 {
     /* @var \Webburza\Sylius\LocationBundle\Doctrine\ORM\LocationRepository $locationRepository */
     $locationRepository = $this->container->get('webburza_location.repository.location');
     /* @var \Sylius\Component\Locale\Model\Locale */
     $locale = $this->get('sylius.context.locale')->getCurrentLocale();
     /* @var \Symfony\Component\Serializer\Serializer */
     $serializer = $this->container->get('serializer');
     if ($query = $request->get('query')) {
         $locations = $locationRepository->findPublicByQuery($query, $locale);
     } else {
         $locations = $locationRepository->findPublicByQuery('', $locale);
     }
     $locationsJson = $serializer->serialize($locations, 'json');
     $returnJson = AcceptHeader::fromString($request->headers->get('Accept'))->has('application/json');
     if ($returnJson) {
         $response = new JsonResponse($locationsJson);
         $response->headers->set('Access-Control-Allow-Origin', '*');
         return $response;
     } else {
         $googleMapsKey = $this->getParameter('webburza.sylius.location_bundle.google_maps_key');
         $googleMapsEnabled = $this->getParameter('webburza.sylius.location_bundle.google_maps_enabled');
         return $this->render('WebburzaSyliusLocationBundle:Frontend:_search.html.twig', ['locations' => $locations, 'locationsJson' => $locationsJson, 'googleMapsEnabled' => $googleMapsEnabled, 'googleMapsKey' => $googleMapsKey]);
     }
 }

作者:GrizliK198    项目:symfony-certification-prepare-projec   
public function viewAction(Request $request)
 {
     $accept = AcceptHeader::fromString($request->headers->get('accept'));
     $finder = new Finder();
     $userFiles = $finder->in(STORAGE_PATH)->name('*.json')->sortByModifiedTime()->files();
     $users = function () use($userFiles) {
         foreach ($userFiles as $userFile) {
             /** @var SplFileInfo $userFile */
             $data = json_decode($userFile->getContents(), true);
             $data['dob'] = new \DateTime($data['dob']['date']);
             $data['id'] = $userFile->getBasename('.json');
             (yield $data);
         }
     };
     $response = new Response();
     if ($accept->has('text/html')) {
         $response->setContent($this->getTwig()->render('crud/view.html.twig', ['users' => $users(), 'urlGenerator' => $this->urlGenerator(), 'translator' => TranslationFactory::createTranslator($request), 'user' => $this->getUser()]));
     } elseif ($accept->has('application/json')) {
         $response = new Response('', Response::HTTP_OK, ['Content-Type' => 'application/json']);
         $userList = iterator_to_array($users());
         $response->setContent(json_encode($userList));
     } elseif ($accept->has('text/xml')) {
         $response = new Response('', Response::HTTP_OK, ['Content-Type' => 'text/xml']);
         $userList = iterator_to_array($users());
         $xml = new \SimpleXMLElement('<root />');
         array_walk($userList, function ($userData) use($xml) {
             $user = $xml->addChild('user');
             $user->addChild('username', $userData['username']);
         });
         $response->setContent($xml->asXML());
     }
     return $response;
 }

作者:czi    项目:laravel-jsonap   
/**
  * @param Request $request
  * @return bool
  */
 protected function contentTypeHeaderValid(Request $request)
 {
     $contentTypeHeader = AcceptHeader::fromString($request->header('content-type'));
     if ($contentTypeHeader->has('application/vnd.api+json')) {
         $attributes = $contentTypeHeader->get('application/vnd.api+json')->getAttributes();
         return empty($attributes) || count($attributes) === 1 && $contentTypeHeader->get('application/vnd.api+json')->getAttribute('charset') === 'UTF-8';
     }
     return false;
 }

作者:sobola    项目:rest-negotiato   
private function parseFormatFromHeader(Request $request, $headerName)
 {
     if (!$request->headers->has($headerName)) {
         //if there is no header with the specified name, fall-back on the default format
         return self::DEFAULT_FORMAT;
     }
     $acceptHeader = AcceptHeader::fromString($request->headers->get($headerName))->first();
     $format = $acceptHeader->getAttribute('format', null);
     return is_null($format) ? self::DEFAULT_FORMAT : $format;
 }

作者:cotaprec    项目:kerne   
/**
  * @param  GetResponseEvent $event
  * @return null
  */
 public function onRequest(GetResponseEvent $event)
 {
     if (!$event->isMasterRequest()) {
         return null;
     }
     $accept = AcceptHeader::fromString($event->getRequest()->headers->get('Accept'));
     if ($accept->has('*/*') || $accept->has('application/json')) {
         return null;
     }
     $event->setResponse($this->responseToSend);
 }

作者:elibert    项目:api-bundl   
/**
  * @param Request $request
  * @param $version
  * @return mixed
  */
 public function getVersionByAcceptHeaders(Request $request, $version)
 {
     $acceptHeader = AcceptHeader::fromString($request->headers->get('Accept'))->all();
     foreach ($acceptHeader as $acceptHeaderItem) {
         if ($acceptHeaderItem->hasAttribute('version')) {
             $version = $acceptHeaderItem->getAttribute('version');
             break;
         }
     }
     return $version;
 }

作者:erpframewor    项目:restap   
/**
  * Returns the API version.
  *
  * @return int $version
  *   The version number of the API (default: 1).
  *
  */
 public function getVersion()
 {
     $version = 1;
     $accept = AcceptHeader::fromString($this->headers->get('accept'));
     // We'll assume the first accept header to have a version is accurate.
     foreach ($accept->all() as $item) {
         if ($item->getAttribute('version')) {
             $version = $item->getAttribute('version');
             break;
         }
     }
     return $version;
 }

作者:elibert    项目:api-bundl   
/**
  * @param Request $request
  *
  * @return mixed|string
  */
 public function getContext(Request $request = null)
 {
     $context = 'ld-json';
     if (null !== $request) {
         $acceptHeader = AcceptHeader::fromString($request->headers->get('Accept'))->all();
         foreach ($acceptHeader as $acceptHeaderItem) {
             if ($acceptHeaderItem->hasAttribute('version')) {
                 $context = str_ireplace('application/', '', $acceptHeaderItem->getValue());
                 break;
             }
         }
     }
     return $context;
 }

作者:alebo    项目:gravito   
/**
  * parse Accept-Language header from request.
  *
  * @param GetResponseEvent $event listener event
  *
  * @return void
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $headers = AcceptHeader::fromString($request->headers->get('Accept-Language'));
     $languages = array_intersect(array_map(function ($header) {
         return $header->getValue();
     }, $headers->all()), array_map(function ($language) {
         return $language->getId();
     }, $this->repository->findAll()));
     if (empty($languages)) {
         $languages[$this->defaultLocale] = $this->defaultLocale;
     }
     $request->attributes->set('languages', $languages);
 }

作者:elibert    项目:api-bundl   
/**
  * @param Request $request
  *
  * @return mixed|string
  */
 public function getVersion(Request $request = null)
 {
     $version = 'v2';
     if ($request instanceof Request) {
         $acceptHeader = AcceptHeader::fromString($request->headers->get('Accept'))->all();
         foreach ($acceptHeader as $acceptHeaderItem) {
             if ($acceptHeaderItem->hasAttribute('version')) {
                 $version = $acceptHeaderItem->getAttribute('version');
                 break;
             }
         }
     }
     return $version;
 }

作者:devd    项目:sign   
/**
  * Check the content-type header.
  *
  * @param  string $content
  * @return boolean
  */
 public function checkContentTypeHeader($content)
 {
     $header = AcceptHeader::fromString($content);
     if (!$header->has(self::CONTENT_TYPE)) {
         throw new InvalidJsonApiContentTypeHeader();
     }
     $attributes = $header->get(self::CONTENT_TYPE)->getAttributes();
     if (count($attributes) > 1) {
         throw new InvalidJsonApiContentTypeHeaderParameterCount();
     }
     if (count($attributes) === 1 && $header->get(self::CONTENT_TYPE)->getAttribute('charset') !== 'UTF-8') {
         throw new InvalidJsonApiContentTypeHeaderCharset();
     }
     return true;
 }

作者:sobola    项目:rest-negotiato   
private function getVersion(Request $request, $headerName)
 {
     if (!$request->headers->has($headerName)) {
         return null;
     }
     $acceptHeader = AcceptHeader::fromString($request->headers->get($headerName))->first();
     $version = $acceptHeader->getAttribute('version', null);
     if (!is_null($version)) {
         if (!ctype_digit((string) $version)) {
             throw new UnsupportedVersionException(sprintf('Version %s is invalid', $version), UnsupportedVersionException::CODE);
         }
         return (int) $version;
     }
     return null;
 }

作者:shreyans26    项目:symfonyPlayGroun   
/**
  * Detect the request format based on the priorities and the Accept header
  *
  * Note: Request "_format" parameter is considered the preferred Accept header
  *
  * @param   Request     $request          The request
  * @param   array       $priorities       Ordered array of formats (highest priority first)
  * @param   Boolean     $preferExtension  If to consider the extension last or first
  *
  * @return  void|string                 The format string
  */
 public function getBestFormat(Request $request, array $priorities, $preferExtension = false)
 {
     // BC - Maintain this while 2.0 and 2.1 dont reach their end of life
     // Note: Request::splitHttpAcceptHeader is deprecated since version 2.2, to be removed in 2.3.
     if (class_exists('Symfony\\Component\\HttpFoundation\\AcceptHeader')) {
         $mimetypes = array();
         foreach (AcceptHeader::fromString($request->headers->get('Accept'))->all() as $item) {
             $mimetypes[$item->getValue()] = $item->getQuality();
         }
     } else {
         $mimetypes = $request->splitHttpAcceptHeader($request->headers->get('Accept'));
     }
     $extension = $request->get('_format');
     if (null !== $extension && $request->getMimeType($extension)) {
         $mimetypes[$request->getMimeType($extension)] = $preferExtension ? reset($mimetypes) + 1 : end($mimetypes) - 1;
         arsort($mimetypes);
     }
     if (empty($mimetypes)) {
         return null;
     }
     $catchAllEnabled = in_array('*/*', $priorities);
     return $this->getFormatByPriorities($request, $mimetypes, $priorities, $catchAllEnabled);
 }

作者:mesusha    项目:FirstRep   
/**
  * Gets a list of content types acceptable by the client browser.
  *
  * @return array List of content types in preferable order
  *
  * @api
  */
 public function getAcceptableContentTypes()
 {
     if (null !== $this->acceptableContentTypes) {
         return $this->acceptableContentTypes;
     }
     return $this->acceptableContentTypes = array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all());
 }

作者:eltrin    项目:platfor   
/**
  * @return array
  */
 public function getAcceptedLocales()
 {
     if (!$this->acceptLanguageHeader) {
         return [];
     }
     return array_keys(AcceptHeader::fromString($this->acceptLanguageHeader)->all());
 }

作者:nextmotio    项目:symfon   
/**
  * Splits an Accept-* HTTP header.
  *
  * @param string $header Header to split
  *
  * @return array Array indexed by the values of the Accept-* header in preferred order
  *
  * @deprecated Deprecated since version 2.2, to be removed in 2.3.
  */
 public function splitHttpAcceptHeader($header)
 {
     $headers = array();
     foreach (AcceptHeader::fromString($header)->all() as $item) {
         $key = $item->getValue();
         foreach ($item->getAttributes() as $name => $value) {
             $key .= sprintf(';%s=%s', $name, $value);
         }
         $headers[$key] = $item->getQuality();
     }
     return $headers;
 }

作者:woei6    项目:platfor   
/**
  * Returns Accept-Language header from headers.
  *
  * @param Headers $headers
  *
  * @return string
  */
 protected function getAcceptLanguageHeader(Headers $headers)
 {
     $header = $headers->get('Accept-Language');
     if ($header === false) {
         return '';
     } elseif (!$header instanceof \ArrayIterator) {
         $header = new \ArrayIterator([$header]);
     }
     $items = [];
     $header->rewind();
     while ($header->valid()) {
         $items[] = AcceptHeaderItem::fromString($header->current()->getFieldValue());
         $header->next();
     }
     $acceptHeader = new AcceptHeader($items);
     return $acceptHeader->__toString();
 }

作者:sgulset    项目:imb   
/**
  * Perform content negotiation by looking the the current URL and the Accept request header
  *
  * @param EventInterface $event The event instance
  */
 public function negotiate(EventInterface $event)
 {
     $request = $event->getRequest();
     $response = $event->getResponse();
     $formatter = null;
     $extension = $request->getExtension();
     $routeName = (string) $request->getRoute();
     $config = $event->getConfig();
     $contentNegotiateImages = $config['contentNegotiateImages'];
     $model = $response->getModel();
     if (!$extension && !$contentNegotiateImages && $model instanceof Model\Image) {
         // Configuration is telling us not to use content negotiation for images,
         // instead we want to use the original format of the image
         $mime = $model->getMimeType();
         $formatter = $this->supportedTypes[$mime];
     } else {
         if ($extension && !($model instanceof Model\Error && $routeName === 'image')) {
             // The user agent wants a specific type. Skip content negotiation completely, but not
             // if the request is against the image resource, and ended up as an error, because then
             // Imbo would try to render the error as an image.
             $mime = $this->defaultMimeType;
             if (isset($this->extensionsToMimeType[$extension])) {
                 $mime = $this->extensionsToMimeType[$extension];
             }
             $formatter = $this->supportedTypes[$mime];
         } else {
             // Set Vary to Accept since we are doing content negotiation based on Accept
             $response->setVary('Accept', false);
             // No extension have been provided
             $acceptableTypes = array();
             foreach (AcceptHeader::fromString($request->headers->get('Accept', '*/*'))->all() as $item) {
                 $acceptableTypes[$item->getValue()] = $item->getQuality();
             }
             $match = false;
             $maxQ = 0;
             // Specify which types to check for since all models can't be formatted by all
             // formatters
             $modelClass = get_class($model);
             $modelType = strtolower(substr($modelClass, strrpos($modelClass, '\\') + 1));
             $types = $this->defaultModelTypes;
             if (isset($this->modelTypes[$modelType])) {
                 $types = $this->modelTypes[$modelType];
             }
             // If we are dealing with images we want to make sure the original mime type of the
             // image is checked first. If the client does not really have any preference with
             // regards to the mime type (*/* or image/*) this results in the original mime type of
             // the image being sent.
             if ($model instanceof Model\Image) {
                 $original = $model->getMimeType();
                 if ($types[0] !== $original) {
                     $types = array_filter($types, function ($type) use($original) {
                         return $type !== $original;
                     });
                     array_unshift($types, $original);
                 }
             }
             foreach ($types as $mime) {
                 if (($q = $this->contentNegotiation->isAcceptable($mime, $acceptableTypes)) && $q > $maxQ) {
                     $maxQ = $q;
                     $match = true;
                     $formatter = $this->supportedTypes[$mime];
                 }
             }
             if (!$match && !$event->hasArgument('noStrict')) {
                 // No types matched with strict mode enabled. The client does not want any of Imbo's
                 // supported types. Y U NO ACCEPT MY TYPES?! FFFFUUUUUUU!
                 throw new Exception\RuntimeException('Not acceptable', 406);
             } else {
                 if (!$match) {
                     // There was no match but we don't want to be an ass about it. Send a response
                     // anyway (allowed according to RFC2616, section 10.4.7)
                     $formatter = $this->supportedTypes[$this->defaultMimeType];
                 }
             }
         }
     }
     $this->formatter = $formatter;
 }

作者:ronnyl    项目:symfon   
/**
  * Splits an Accept-* HTTP header.
  *
  * @param string $header Header to split
  *
  * @return array Array indexed by the values of the Accept-* header in preferred order
  *
  * @deprecated Deprecated since version 2.2, to be removed in 2.3.
  */
 public function splitHttpAcceptHeader($header)
 {
     trigger_error('splitHttpAcceptHeader() is deprecated since version 2.2 and will be removed in 2.3.', E_USER_DEPRECATED);
     $headers = array();
     foreach (AcceptHeader::fromString($header)->all() as $item) {
         $key = $item->getValue();
         foreach ($item->getAttributes() as $name => $value) {
             $key .= sprintf(';%s=%s', $name, $value);
         }
         $headers[$key] = $item->getQuality();
     }
     return $headers;
 }

作者:Ener-Getic    项目:symfon   
/**
  * @dataProvider provideSortingData
  */
 public function testSorting($string, array $values)
 {
     $header = AcceptHeader::fromString($string);
     $this->assertEquals($values, array_keys($header->all()));
 }


问题


面经


文章

微信
公众号

扫码关注公众号