juliangut/negotiate

Negotiation middleware

Fund package maintenance!
juliangut

1.2 2021-03-11 21:55 UTC

This package is auto-updated.

Last update: 2021-06-11 22:45:46 UTC


README

PHP version Latest Version License

Total Downloads Monthly Downloads

Negotiate

Simple and flexible negotiation middleware based on willdurand/negotiation

Installation

Composer

composer require juliangut/negotiate

Usage

Require composer autoload file

require './vendor/autoload.php';

use Jgut\Negotiate\Negotiator;
use Jgut\Negotiate\Scope\Language;
use Jgut\Negotiate\Scope\MediaType;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

$scopes = [
    new MediaType(['text/html', 'application/json']),
    new Language(['en', 'es'], false),
];
/* @var \Psr\Http\Message\ResponseFactoryInterface $responseFactory */

$middleware = new Negotiator($scopes, $responseFactory);
$middleware->setAttributeName('negotiationProvider');

// Request handler
new class() implements RequestHandlerInterface {
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $negotiationProvider = $request->getAttribute('negotiationProvider');

        $negotiationProvider->get('accept'); // \Negotiation\Accept
        $negotiationProvider->getAcceptLanguage(); // \Negotiation\AcceptLanguage
        $negotiationProvider->getAcceptLanguageLine(); // negotiated language string
        $negotiationProvider->getAcceptCharset(); // null, not defined
        
        // ...
    }
};

Scopes

Encapsulate negotiation in a context, for example media type or character set. Give it a list of priorities, and you are good to go.

Additionally, a third parameter controls behaviour if request header is empty or negotiation could not be determined successfully. By default, your list of priorities will be used to create a \Negotiation\AcceptHeader you can use. If set to false a \Jgut\Negotiation\Exception will be thrown and captured by the middleware

Middleware

Middleware requires a list of negotiation scopes. Negotiation will take place in the middleware

  • If everything goes well request will have an attribute with a \Jgut\Negotiate\Provider object
  • If negotiation goes south
    • A 415 response will be returned if Content-Type header negotiation fails
    • A 406 response will be returned if any other negotiation fails

Contributing

Found a bug or have a feature request? Please open a new issue. Have a look at existing issues before.

See file CONTRIBUTING.md

License

See file LICENSE included with the source code for a copy of the license terms.