Negotiation is a standalone library without any dependencies that allows you to implement content negotiation in your application, whatever framework you use. This library is based on RFC 2616. Negotiation is easy to use, and extensively unit tested.
The recommended way to install Negotiation is through Composer:
$ composer require willdurand/negotiationProtip: you can also choose the correct version via
willdurand/negotiation.
In a nutshell:
<?php
$negotiator = new \Negotiation\Negotiator();
$bestHeader = $negotiator->getBest('en; q=0.1, fr; q=0.4, fu; q=0.9, de; q=0.2');
// $bestHeader = 'fu';The getBest() method, part of the NegotiatorInterface, returns either null
or AcceptHeader instances. An AcceptHeader object owns a value and a
quality.
The Format Negotiation is handled by the FormatNegotiator class.
Basically, pass an Accept header and optionally a set of preferred media types
to the getBest() method in order to retrieve the best media type:
<?php
$negotiator = new \Negotiation\FormatNegotiator();
$acceptHeader = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
$priorities = array('text/html', 'application/json', '*/*');
$format = $negotiator->getBest($acceptHeader, $priorities);
// $format->getValue() = text/htmlThe FormatNegotiator class also provides a getBestFormat() method that
returns the best format given an Accept header string and a set of
preferred/allowed formats or mime types:
<?php
$negotiator = new \Negotiation\FormatNegotiator();
$acceptHeader = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
$priorities = array('html', 'application/json', '*/*');
$format = $negotiator->getBestFormat($acceptHeader, $priorities);
// $format = htmlregisterFormat($format, array $mimeTypes, $override = false): registers a new format with its mime types;getFormat($mimeType): returns the format for a given mime type, or null if not found;normalizePriorities($priorities): ensures that any formats are converted to mime types.
Language negotiation is handled by the LanguageNegotiator class:
<?php
$negotiator = new \Negotiation\LanguageNegotiator();
$language = $negotiator->getBest('da, en-gb;q=0.8, en;q=0.7');
// $language = daCharset/Encoding negotiation works out of the box using the Negotiator class:
<?php
$negotiator = new \Negotiation\Negotiator();
$priorities = array(
'utf-8',
'big5',
'shift-jis',
);
$bestHeader = $negotiator->getBest('ISO-8859-1, Big5;q=0.6,utf-8;q=0.7, *;q=0.5', $priorities);
// $bestHeader = 'utf-8'Setup the test suite using Composer:
$ composer install --dev
Run it using PHPUnit:
$ phpunit
See CONTRIBUTING file.
-
Some parts of this library are inspired by:
- Symfony framework;
- FOSRest;
- PEAR HTTP2.
-
William Durand william.durand1@gmail.com
Negotiation is released under the MIT License. See the bundled LICENSE file for details.


