usox / language-negotiator
Negotiate http client language
1.0.0
2022-01-30 12:27 UTC
Requires
- php: ^8.0||^8.1
- psr/http-server-middleware: ^1.0
Requires (Dev)
- phpstan/phpstan: ^1.4
- phpunit/phpunit: ^9.5
README
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);