<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
lcobucci / content-negotiation-middleware example snippets
declare(strict_types=1);
use Lcobucci\ContentNegotiation\ContentTypeMiddleware;
use Lcobucci\ContentNegotiation\Formatter\Json;
use Lcobucci\ContentNegotiation\Formatter\StringCast;
use Laminas\Diactoros\StreamFactory;
$middleware = ContentTypeMiddleware::fromRecommendedSettings(
// First argument is the list of formats you want to support:
[
'json',
// You may also specify the full configuration of the format.
// That's handy if you need to add extensions or mime-types:
'html' => [
'extension' => ['html', 'htm', 'php'],
'mime-type' => ['text/html', 'application/xhtml+xml'],
'charset' => true,
],
],
// It's very important to mention that:
//
// * the first format will be used as fallback (no acceptable mime type
// found)
// * the order of elements does matter
// * the first element of `mime-type` list will be used as negotiated type
// The second argument is the list of formatters that will be used for
// each mime type:
[
'application/json' => new Json(),
'text/html' => new StringCast(),
],
// The last argument is any implementation for the StreamFactoryInterface (PSR-17)
new StreamFactory()
);
// ...
$application->pipe($middleware);
declare(strict_types=1);
namespace Me\MyApp;
use Fig\Http\Message\StatusCodeInterface;
use Lcobucci\ContentNegotiation\UnformattedResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Laminas\Diactoros\Response;
final class MyHandler implements RequestHandlerInterface
{
public function handle(ServerRequestInterface $request): ResponseInterface
{
// Does the necessary process and creates `$result` with the unformatted
// content.
return new UnformattedResponse(
(new Response())->withStatus(StatusCodeInterface::STATUS_CREATED),
$result
);
}
}
declare(strict_types=1);
namespace Me\MyApp;
use Lcobucci\ContentNegotiation\Formatter;
use Lcobucci\ContentNegotiation\UnformattedResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamFactoryInterface;
final class MyFancyFormatter implements Formatter
{
public function format(UnformattedResponse $response, StreamFactoryInterface $streamFactory): ResponseInterface
{
$content = ''; // Do some fancy formatting of $response->getUnformattedContent() and put into $content
return $response->withBody($streamFactory->createStream($content));
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.