Content Negociation
The [ContentNegociation](NoreSources\Http\ContentNegociation\ContentNegociator) class
returns the preferred Content-* header values according
the Accept-* header values of a HTTP request and the server supported content formats.
| Request header | → | Response header |
|---|---|---|
| Accept | Content-Type | |
| Accept-Charser | Content-Type `charset` parameter | |
| Accept-Encoding | Content-Encoding | |
| Accept-Language | Content-Language |
Example
use NoreSources\Http\ContentNegociation\ContentNegociator;
use NoreSources\Http\Header\HeaderField;
use Psr\Http\Message\ServerRequestInterface;
// A router request controller
function handleRequest (ServerRequestInterface $request)
{
$supportedMediaTypes = [
/* List of media types */
'application/json',
'text/yaml',
'text/html'
];
$supportedLanguage = [
/* List of language tags */
'fr-FR', 'en-UK', 'en-US'
];
$negociator = ContentNegociator::getInstance();
$negociation = $negociator->negociate($request, [
HeaderField::CONTENT_TYPE => $supportedMediaTypes,
HeaderField::CONTENT_LANGUAGE => $supportedLanguage
]);
// Build content according result of negociation
$content = getResponseContentFor ($negociation);
// Build response with content and headers
// returned by negociation
$response = new TextResponse($content);
foreach ($negociation as $header => $value)
$response = $response->withHeader ($header, \strval($value));
return $response;
}