Skip to content

Negotiates the client request language

License

Notifications You must be signed in to change notification settings

usox/language-negotiator

Repository files navigation

Unittests Scrutinizer Code Quality Code Coverage

language-negotiator

Negotiates the client language of a http request using the Accept-Language http header.

Installation

composer require usox/language-negotiator

Usage

There are several ways to use the negotiator.

With $_SERVER superglobal in constructor

use Usox\LanguageNegotiator\LanguageNegotiator;

$negotiator = new LanguageNegotiator(
    ['en', 'de'], // array of supported languages
    'en' // fallback language,
    $_SERVER
);

$clientLanguage = $negotiator->negotiate();

With an already obtained http headers array (or $_SERVER)

use Usox\LanguageNegotiator\LanguageNegotiator;

$negotiator = new LanguageNegotiator(
    ['en', 'de'], // array of supported languages
    'en' // fallback language,
);

$clientLanguage = $negotiator->negotiate(
    $_SERVER
);

As PSR15 middleware

The negotiator will automatically enrich ServerRequest with the negotiated client language. It will be added as an attribute which can obtained using the attribute name constant.

use Usox\LanguageNegotiator\LanguageNegotiator;

$negotiator = new LanguageNegotiator(
    ['en', 'de'], // array of supported languages
    'en' // fallback language,
);

// assumes, you have some kind of framework which supports PSR request handling
$myFramework->addMiddleware($negotiator);

// get the language from the psr server request
$clientLanguage = $request->getAttribute(LanguageNegotiator::REQUEST_ATTRIBUTE_NAME);