Common utils used by PSR-15 middlewares
Clone or download
Oscar Otero
Latest commit 7ad4e14 Aug 22, 2018

README.md

middlewares/utils

Latest Version on Packagist Software License Build Status Quality Score Total Downloads SensioLabs Insight

Common utilities used by the middlewares' packages:

Factory

Used to create psr-7 instances of ServerRequestInterface, ResponseInterface, StreamInterface and UriInterface. Detects automatically Diactoros, Guzzle, Slim and Nyholm/psr7 but you can register a different factory using the psr/http-factory interface.

use Middlewares\Utils\Factory;

$request = Factory::createServerRequest('GET', '/');
$response = Factory::createResponse(200);
$stream = Factory::createStream('Hello world');
$uri = Factory::createUri('http://example.com');

// By default, detect diactoros, guzzle, slim and nyholm (in this order of priority),
// but you can change it and add other classes
Factory::setStrategy([
    'MyApp\Psr17Factory'
    Middlewares\Utils\Factory\GuzzleFactory,
    Middlewares\Utils\Factory\DiactorosFactory,
]);

//And also register directly an initialized factory
Factory::setResponseFactory(new FooResponseFactory());

$fooResponse = Factory::createResponse();

//Get the PSR-17 factory used
$uriFactory = Factory::getUriFactory();
$uri = $uriFactory->createUri('http://hello-world.com');

Dispatcher

Minimalist PSR-15 compatible dispatcher. Used for testing purposes.

use Middlewares\Utils\Dispatcher;

$response = Dispatcher::run([
    new Middleware1(),
    new Middleware2(),
    new Middleware3(),
    function ($request, $next) {
        $response = $next->handle($request);
        return $response->withHeader('X-Foo', 'Bar');
    }
]);

CallableHandler

To resolve and execute a callable. It can be used as a middleware, server request handler or a callable:

use Middlewares\Utils\CallableHandler;

$callable = new CallableHandler(function () {
    return 'Hello world';
});

$response = $callable();

echo $response->getBody(); //Hello world

HttpErrorException

General purpose exception used to represent HTTP errors.

use Middlewares\Utils\HttpErrorException;

$exception = HttpErrorException::create(500, [
    'problem' => 'Something bad happened',
]);

// Additional context can be get and set on the exception
$context = $exception->getContext();

Traits

Common utilities shared between many middlewares like the ability to customize PSR-17 factories.

  • HasResponseFactory
  • HasStreamFactory

Please see CHANGELOG for more information about recent changes and CONTRIBUTING for contributing details.

The MIT License (MIT). Please see LICENSE for more information.