本文整理汇总了PHP中Symfony\Component\HttpFoundation\Request::getLanguages方法的典型用法代码示例。如果您正苦于以下问题:PHP Request::getLanguages方法的具体用法?PHP Request::getLanguages怎么用?PHP Request::getLanguages使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Symfony\Component\HttpFoundation\Request
的用法示例。
在下文中一共展示了Request::getLanguages方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: switchAction
/**
* Action for locale switch
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @param $_locale The locale to set
*
* @return \Symfony\Bundle\FrameworkBundle\Controller\RedirectResponse
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function switchAction(Request $request, $_locale)
{
// Check if the Language is allowed
if (!in_array(\Locale::getPrimaryLanguage($_locale), $this->allowedLanguages)) {
throw new NotFoundHttpException('This language is not available');
}
// tries to detect a Region from the user-provided locales
$providedLanguages = $request->getLanguages();
$locales = array();
foreach ($providedLanguages as $locale) {
if (strpos($locale . '_', $_locale) !== false && strlen($locale) > 2) {
$locales[] = $locale;
}
}
if (count($locales) > 0) {
$this->session->set('localeIdentified', $locales[0]);
} else {
$this->session->set('localeIdentified', $_locale);
}
// Add the listener
$this->session->set('setLocaleCookie', true);
// Redirect the User
if ($request->headers->has('referer') && true === $this->useReferrer) {
return new RedirectResponse($request->headers->get('referer'));
}
if (null !== $this->redirectToRoute) {
return new RedirectResponse($this->router->generate($this->redirectToRoute));
}
return new RedirectResponse($request->getScheme() . '://' . $request->getHttpHost() . $this->redirectToUrl);
}
示例2: guessLocale
/**
* Guess the locale based on the browser settings
*
* @param Request $request
*
* @return boolean
*/
public function guessLocale(Request $request)
{
$validator = $this->metaValidator;
// Get the preferred locale from the Browser.
$preferredLocale = $request->getPreferredLanguage();
$availableLocales = $request->getLanguages();
if (!$preferredLocale or count($availableLocales) === 0) {
return false;
}
// If the preferred primary locale is allowed, return the locale.
if ($validator->isAllowed($preferredLocale)) {
$this->identifiedLocale = $preferredLocale;
return true;
}
// Get a list of available and allowed locales and return the first result
$matchLocale = function ($v) use($validator) {
return $validator->isAllowed($v);
};
$result = array_values(array_filter($availableLocales, $matchLocale));
if (!empty($result)) {
$this->identifiedLocale = $result[0];
return true;
}
return false;
}
示例3: getRequestPreferredLanguage
private function getRequestPreferredLanguage(Request $request)
{
foreach ($request->getLanguages() as $language) {
if (preg_match('/^[a-z]{2,3}$/i', $language)) {
return $language;
}
}
}
示例4: createContexts
public function createContexts(Request $request)
{
$map = array('request_method' => $request->getMethod(), 'request_uri' => $request->getRequestUri(), 'request_route' => $request->attributes->get('_route'), 'request_host' => $request->getHost(), 'request_port' => $request->getPort(), 'request_scheme' => $request->getScheme(), 'request_client_ip' => $request->getClientIp(), 'request_content_type' => $request->getContentType(), 'request_acceptable_content_types' => $request->getAcceptableContentTypes(), 'request_etags' => $request->getETags(), 'request_charsets' => $request->getCharsets(), 'request_languages' => $request->getLanguages(), 'request_locale' => $request->getLocale(), 'request_auth_user' => $request->getUser(), 'request_auth_has_password' => !is_null($request->getPassword()));
// Attributes from newer versions.
if (method_exists($request, 'getEncodings')) {
$map['request_encodings'] = $request->getEncodings();
}
if (method_exists($request, 'getClientIps')) {
$map['request_client_ips'] = $request->getClientIps();
}
return $map;
}
示例5: getTranslationsFields
/**
* @param $object
* @param $field
* @return mixed
*/
public function getTranslationsFields($object, $field)
{
if ($this->objectTranslations[$object->getId()]->count() > 0) {
return $this->getCurrentTranslation($object, $field);
}
$repoTranslation = $this->em->getRepository('Gedmo\\Translatable\\Entity\\Translation');
$languages = array_merge($this->request->getLanguages(), [$this->request->getDefaultLocale()]);
$elements = $repoTranslation->findBy(['foreignKey' => $object->getId(), 'objectClass' => get_class($object), 'locale' => $languages]);
foreach ($elements as $element) {
$this->objectTranslations[$object->getId()]->add($element);
}
return $this->getCurrentTranslation($object, $field);
}
示例6: logRequest
protected function logRequest(Request $request)
{
$msg = 'Request "{request_method} {request_uri}"';
$map = array('request_method' => $request->getMethod(), 'request_uri' => $request->getRequestUri(), 'request_host' => $request->getHost(), 'request_port' => $request->getPort(), 'request_scheme' => $request->getScheme(), 'request_client_ip' => $request->getClientIp(), 'request_content_type' => $request->getContentType(), 'request_acceptable_content_types' => $request->getAcceptableContentTypes(), 'request_etags' => $request->getETags(), 'request_charsets' => $request->getCharsets(), 'request_languages' => $request->getLanguages(), 'request_locale' => $request->getLocale(), 'request_auth_user' => $request->getUser(), 'request_auth_has_password' => !is_null($request->getPassword()));
// Attributes from newer versions.
if (method_exists($request, 'getEncodings')) {
$map['request_encodings'] = $request->getEncodings();
}
if (method_exists($request, 'getClientIps')) {
$map['request_client_ips'] = $request->getClientIps();
}
$this->logger->log($this->logLevel, $msg, $map);
}
示例7: rootAction
/**
* redirect to the browser locale if found
*
* @Route("/")
*
* @param Request $request
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function rootAction(Request $request)
{
$locales = $this->getParameter('locales');
$languages = $request->getLanguages();
$locale = null;
foreach ($languages as $language) {
$lang = strtolower(substr($language, 0, 2));
if ($lang && in_array($lang, $locales)) {
$locale = $lang;
break;
}
}
if (empty($locale)) {
$locale = $this->getParameter('locale');
}
return $this->redirect('/' . $locale . '/');
}
示例8: getBaseLanguage
/**
* Fetches the base language used to copy the entities
*
* @return \RedKiteLabs\RedKiteCms\RedKiteCmsBundle\Model\Language
*/
protected function getBaseLanguage()
{
$languageRepository = $this->languageManager->getLanguageRepository();
// Tries to fetch the current language from the request
if (null !== $this->request) {
$languages = $this->request->getLanguages();
$alLanguage = $languageRepository->fromLanguageName($languages[1]);
if (null !== $alLanguage) {
return $alLanguage;
}
// @codeCoverageIgnoreStart
}
// @codeCoverageIgnoreEnd
// Fetches the current language from the main language when the adding one is not the main language
if ($this->mainLanguage->getId() != $this->languageManager->get()->getId()) {
return $this->mainLanguage;
}
return $languageRepository->firstOne();
}
示例9: indexAction
public function indexAction(Request $request, Application $app)
{
$requestVars = $request->request->all();
$requestVars['server']['locale'] = $this->extractLocale($request->getLanguages());
$inventory = $this->getInventory($requestVars);
$varsFile = new VarfileRenderer('all');
$playbook = new PlaybookRenderer();
// @todo fix str_replace
$playbook->setVarsFilename(str_replace('ansible/', '', $varsFile->getFilePath()));
$this->getVagrantBundle()->setPlaybook($playbook)->setVarsFile($varsFile)->setInventory($inventory);
$app['roles']->setupRole($requestVars, $this->getVagrantBundle());
$playbook->addRole('app');
$zipPath = tempnam(sys_get_temp_dir(), "phansible_bundle_");
if ($this->getVagrantBundle()->generateBundle($zipPath, $playbook->getRoles())) {
$vagrantfile = $this->getVagrantBundle()->getVagrantFile();
return $this->outputBundle($zipPath, $app, $vagrantfile->getName());
}
return new Response('An error occurred.');
}
示例10: resolveLocale
/**
* {@inheritDoc}
*/
public function resolveLocale(Request $request, array $availableLocales)
{
if ($this->hostMap && isset($this->hostMap[$host = $request->getHost()])) {
return $this->hostMap[$host];
}
// if a locale has been specifically set as a query parameter, use it
if ($request->query->has('hl')) {
$hostLanguage = $request->query->get('hl');
if (preg_match('#^[a-z]{2}(?:_[a-z]{2})?$#i', $hostLanguage)) {
return $hostLanguage;
}
}
// check if a session exists, and if it contains a locale
if ($request->hasPreviousSession()) {
$session = $request->getSession();
if ($session->has('_locale')) {
return $session->get('_locale');
}
}
// if user sends a cookie, use it
if ($request->cookies->has($this->cookieName)) {
$hostLanguage = $request->cookies->get($this->cookieName);
if (preg_match('#^[a-z]{2}(?:_[a-z]{2})?$#i', $hostLanguage)) {
return $hostLanguage;
}
}
// use accept header for locale matching if sent
if ($languages = $request->getLanguages()) {
foreach ($languages as $lang) {
if (in_array($lang, $availableLocales, true)) {
return $lang;
}
$langShort = explode('_', $lang)[0];
if (in_array($langShort, $availableLocales, true)) {
return $langShort;
}
}
}
return null;
}
示例11: testGetLanguages
public function testGetLanguages()
{
$request = new Request();
$this->assertEquals(array(), $request->getLanguages());
$request = new Request();
$request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6');
$this->assertEquals(array('zh', 'en_US', 'en'), $request->getLanguages());
$this->assertEquals(array('zh', 'en_US', 'en'), $request->getLanguages());
$request = new Request();
$request->headers->set('Accept-language', 'zh, i-cherokee; q=0.6');
$this->assertEquals(array('zh', 'cherokee'), $request->getLanguages());
}
示例12: onKernelRequest
public function onKernelRequest(GetResponseEvent $event)
{
$this->event = $event;
$this->request = $event->getRequest();
$rc = $this->router->getRouteCollection();
/* @var $rc \Symfony\Component\Routing\RouteCollection */
$route = $rc->get($this->request->get('_route'));
if (!$route) {
return false;
}
$stats = $route->getOption('stats');
// Verifico che sia stata richiesta la memorizzazione delle statistiche
if ($stats && is_array($stats)) {
// Opzioni default in caso di assenza
$options = array_merge(array('area' => array('default')), $stats);
// trasformo area in un array
if (!is_array($options['area'])) {
$options['area'] = array($options['area']);
}
// Verifico che non siano stati richieste aree "dinamiche" dipendenti da un parametro della route
$route = $this->request->get('_route');
$route_params = $this->request->get('_route_params');
if (isset($options['area_from'])) {
// L'area dinamica deve essere in un array, potrebbe avere anche
// i parametri from e chars necessari a prendere una sotto stringa
// del parametro richiesto
if (!is_array($options['area_from'])) {
$options['area_from'] = array('param' => $options['area_from']);
}
// Se il parametro esiste, vado avanti e configuro la nuova area
if (isset($route_params[$options['area_from']['param']])) {
$area = $route_params[$options['area_from']['param']];
if (isset($options['area_from']['from']) && isset($options['area_from']['chars'])) {
$area = substr($area, $options['area_from']['from'], $options['area_from']['chars']);
}
// Se c'è solo l'area default l'unica area che verrà memorizzata
// sarà quella dinamica, altrimenti aggiungo all'array delle aree
if (count($options['area']) == 1 && $options['area'][0] == 'default') {
$options['area'][0] = $area;
} else {
$options['area'][] = $area;
}
}
}
if (isset($options['entity'])) {
// Controllo e parametrizzo l'entity
if (!is_array($options['entity'])) {
$options['entity'] = array('entity' => $options['entity'], 'prefix' => $options['entity'], 'column' => 'id', 'param' => 'id', 'output' => 'id');
} else {
$options['entity'] = array_merge(array('entity' => $options['entity']['entity'], 'prefix' => $options['entity']['entity'], 'column' => 'id', 'param' => 'id', 'output' => 'id'), $options['entity']);
}
// Se il parametro esiste, vado avanti e configuro la nuova area
if (isset($route_params[$options['entity']['param']])) {
$param = $route_params[$options['entity']['param']];
$_entity = $this->em->getRepository($options['entity']['entity']);
$entity = $_entity->findOneBy(array($options['entity']['column'] => $param));
$fx = \Doctrine\Common\Util\Inflector::camelize("get_" . $options['entity']['output']);
$area = $options['entity']['prefix'] . '-' . $entity->{$fx}();
// Se c'è solo l'area default l'unica area che verrà memorizzata
// sarà quella dinamica, altrimenti aggiungo all'array delle aree
if (count($options['area']) == 1 && $options['area'][0] == 'default') {
$options['area'][0] = $area;
} else {
$options['area'][] = $area;
}
}
}
$_url = $this->router->generate($route, $route_params);
$test = preg_match('/.(php|jsp|asp|aspx|html|jpg|jpeg|gif|png)$/', $_url);
if ($test == 0) {
try {
$this->em->beginTransaction();
$visita = new \Ephp\StatsBundle\Entity\Visita();
$visita->setUrl($_url);
$visita->setRoute($route);
$visita->setRouteParams($route_params);
$visita->setSession($this->request->getSession()->getId());
$visita->setIp($this->request->getClientIp());
$visita->setUserAgent($this->request->server->get('HTTP_USER_AGENT'));
$locale = $this->request->getLanguages();
$visita->setLocale(array_shift($locale));
foreach ($options['area'] as $_area) {
$area = $this->em->getRepository('EphpStatsBundle:Area')->findOneBy(array('area' => $_area));
if (!$area) {
$area = new \Ephp\StatsBundle\Entity\Area();
$area->setArea($_area);
$this->em->persist($area);
$this->em->flush();
}
$visita->addAree($area);
}
$this->em->persist($visita);
$this->em->flush();
$this->em->commit();
} catch (\Exception $e) {
\Ephp\UtilityBundle\Utility\Debug::vd($e);
$this->em->rollback();
throw $e;
}
}
//.........这里部分代码省略.........
示例13: getLocale
/**
* @param HttpRequest $request
*
* @return string
*/
public function getLocale(HttpRequest $request)
{
if ($this->locale) {
return $this->locale;
}
// get locale from language list
$constraint = new Locale();
foreach ($request->getLanguages() as $language) {
if (!$this->validator->validate($language, $constraint)->has(0)) {
return $language;
}
}
// get default locale
return $request->getLocale();
}
示例14: runLocaleGuessing
/**
* Loops through all the activated Locale Guessers and
* calls the guessLocale methode and passing the current request.
*
* @param Request $request
*
* @throws InvalidConfigurationException
*
* @return boolean false if no locale is identified
* @return bool the locale identified by the guessers
*/
public function runLocaleGuessing(Request $request)
{
$this->preferredLocales = $request->getLanguages();
foreach ($this->guessingOrder as $guesser) {
if (null === $this->getGuesser($guesser)) {
throw new InvalidConfigurationException(sprintf('Locale guesser service "%s" does not exist.', $guesser));
}
$guesserService = $this->getGuesser($guesser);
$this->logEvent('Locale %s Guessing Service Loaded', ucfirst($guesser));
if (false !== $guesserService->guessLocale($request)) {
$locale = $guesserService->getIdentifiedLocale();
$this->logEvent('Locale has been identified by guessing service: ( %s )', ucfirst($guesser));
return $locale;
}
$this->logEvent('Locale has not been identified by the %s guessing service', ucfirst($guesser));
}
return false;
}
示例15: getSiteAccessFromRequest
/**
* @param Request $request
*
* @return SiteAccess
*/
private function getSiteAccessFromRequest(Request $request)
{
return $this->siteAccessRouter->match(new SimplifiedRequest(array('scheme' => $request->getScheme(), 'host' => $request->getHost(), 'port' => $request->getPort(), 'pathinfo' => $request->getPathInfo(), 'queryParams' => $request->query->all(), 'languages' => $request->getLanguages(), 'headers' => $request->headers->all())));
}