germania-kg/language-negotiation

Middleware to store negotiated client language in a Request attribute.

1.1.0 2023-01-04 08:30 UTC

This package is auto-updated.

Last update: 2024-12-04 12:41:32 UTC


README

Germania KG ยท Language Negotiation

Tests

This middleware stores the result of Will Durand's language Negotiation language in a Request attribute X-language-negotiated.

Works with both PSR-15 SinglePass and traditional Slim-like DoublePass approach.

Usage

Setup

<?php
use Germania\LanguageNegotiation\LanguageNegotiationMiddleware;
use Negotiation\LanguageNegotiator;

$negotiator = new LanguageNegotiator();  
$priorities = array('de', 'fu', 'en');

new LanguageNegotiationMiddleware($negotiator, $priorities);

Configuration using constructor :

// Defaults:
$accept_header = "Accept-Language";
$attr_name = "X-language-negotiated";
$logger = new Monolog // Any PSR-3 Logger; 

new LanguageNegotiationMiddleware($negotiator, $priorities, $accept_header, $attr_name, $logger);

Configuration using methods API:

$middleware = new LanguageNegotiationMiddleware($negotiator, $priorities);
$middleware->setAcceptLanguageHeader("Accept-Language");
$middleware->setRequestAttributeName("X-language-negotiated");
$middleware->setLogger( $psr3_logger );

Usage in Controller

Slim-like example:

<?php
class MyController
{
  public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $args)
  {
    	// S.th. like 'fu'
    	echo $request->getAttribute("X-language-negotiated");
  }
}

Development

$ git clone git@github.com:GermaniaKG/language-negotiation.git
$ cd language-negotiation
$ composer install

Unit tests

Either copy phpunit.xml.dist to phpunit.xml and adapt to your needs, or leave as is. Run PhpUnit test or composer scripts like this:

$ composer test
# or
$ vendor/bin/phpunit