usox/language-negotiator

Negotiate http client language

Fund package maintenance!
usox

1.0.0 2022-01-30 12:27 UTC

This package is auto-updated.

Last update: 2024-04-11 12:03:38 UTC


README

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);