Common utils used by PSR-15 middlewares

Overview

middlewares/utils

Latest Version on Packagist Software License Testing Total Downloads

Common utilities used by the middlewares' packages:

Installation

This package is installable and autoloadable via Composer as middlewares/utils.

composer require middlewares/utils

Factory

Used to create PSR-7 and PSR-17 instances. Detects automatically Diactoros, Guzzle, Slim, Nyholm/psr7 and Sunrise but you can register a different factory using the psr/http-factory interface.

use Middlewares\Utils\Factory;
use Middlewares\Utils\FactoryDiscovery;

// Create PSR-7 instances
$request = Factory::createRequest('GET', '/');
$serverRequest = Factory::createServerRequest('GET', '/');
$response = Factory::createResponse(200);
$stream = Factory::createStream('Hello world');
$uri = Factory::createUri('http://example.com');
$uploadedFile = Factory::createUploadedFile($stream);

// Get PSR-17 instances (factories)
$requestFactory = Factory::getRequestFactory();
$serverRequestFactory = Factory::getServerRequestFactory();
$responseFactory = Factory::getResponseFactory();
$streamFactory = Factory::getStreamFactory();
$uriFactory = Factory::getUriFactory();
$uploadedFileFactory = Factory::getUploadedFileFactory();

// By default, use the FactoryDiscovery class that detects diactoros, guzzle, slim, nyholm and sunrise (in this order of priority),
// but you can change it and add other libraries

Factory::setFactory(new FactoryDiscovery(
    'MyApp\Psr17Factory',
    FactoryDiscovery::SLIM,
    FactoryDiscovery::GUZZLE,
    FactoryDiscovery::DIACTOROS
));

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

$fooResponse = Factory::createResponse();

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;

try {
    $context = ['problem' => 'Something bad happened'];
    throw HttpErrorException::create(500, $context);
} catch (HttpErrorException $exception) {
    $context = $exception->getContext();
}

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

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

Comments
  • composer: allow php ^8.0

    composer: allow php ^8.0

    closes https://github.com/middlewares/utils/issues/22

    Should I send also migration from Travis to GitHub actions? Since Travis is ultra-slow these days and obviously does not have PHP 8.0 ready, GitHub actions are far better nowadays.

    opened by solcik 8
  • Add callable resolvers

    Add callable resolvers

    After thinking about #2 I came up with a bit more complex solution. This solution completely delegates the resolution to one or other resolver, allowing to support resolver specific features (like service id based resolution with a container).

    opened by sagikazarmark 8
  • String conversion problem in CallableHandler

    String conversion problem in CallableHandler

    In case the callable returns a non string-friendly value (not scalars, arrays, objects without __toString, etc) this line will produce a warning: https://github.com/middlewares/utils/blob/master/src/CallableHandler.php#L36

    In that case we should throw an exception, because it's not responsibility of this class to make decisions about how to convert them to string, or delegate that (somehow) to next middleware like "I don't know what to do with this".

    opened by itsjavi 5
  • Dispatcher can implement RequestHandlerInterface

    Dispatcher can implement RequestHandlerInterface

    Hi. Thank you for the great libraries.

    What do you think about making Middlewares\Utils\Dispatcher to implement Psr\Http\Server\RequestHandlerInterface?

    Dispatcher already has method dispatch(ServerRequestInterface $request): ResponseInterface, that, except the name, resemble handle(ServerRequestInterface $request): ResponseInterface from RequestHandlerInterface.

    Making Dispatcher a middleware composite enables to pass it to some runners, for example zendframework/zend-httphandlerrunner:

    $runner = new RequestHandlerRunner(
        $container->get(ApplicationRequestHandler::class),
        $container->get(EmitterStack::class),
        $container->get('ServerRequestFactory'),
        $container->get('ServerRequestErrorResponseGenerator')
    );
    $runner->run();
    

    What do you think about this?

    I have tested such approach localy, so can provide PR if needed.

    Thak you in advance.

    opened by Sevavietl 3
  • zend-diactoros is deprecated by laminas/laminas-diactoros.

    zend-diactoros is deprecated by laminas/laminas-diactoros.

    https://github.com/zendframework/zend-diactoros states :

    Repository abandoned 2019-12-31

    This repository has moved to laminas/laminas-diactoros.

    We should replace

    const DIACTOROS = [
        'request' => 'Zend\Diactoros\RequestFactory',
        'response' => 'Zend\Diactoros\ResponseFactory',
        'serverRequest' => 'Zend\Diactoros\ServerRequestFactory',
        'stream' => 'Zend\Diactoros\StreamFactory',
        'uploadedFile' => 'Zend\Diactoros\UploadedFileFactory',
        'uri' => 'Zend\Diactoros\UriFactory',
    ];
    

    with

    const DIACTOROS = [
        'request' => 'Laminas\Diactoros\RequestFactory',
        'response' => 'Laminas\Diactoros\ResponseFactory',
        'serverRequest' => 'Laminas\Diactoros\ServerRequestFactory',
        'stream' => 'Laminas\Diactoros\StreamFactory',
        'uploadedFile' => 'Laminas\Diactoros\UploadedFileFactory',
        'uri' => 'Laminas\Diactoros\UriFactory',
    ];
    
    opened by DarkMukke 2
  • added slim/psr7 support

    added slim/psr7 support

    opened by jfcherng 2
  • Add

    Add "conflict" option with old http-interop/http-middleware

    This PR fixes #5 by stating that middleware/utils 0.13+ should not be used if "http-interop/http-middleware" is used. This will force a fallback to older versions of middleware/utils.

    opened by moufmouf 2
  • v0.13.0 breaks compatibility with all older middlewares

    v0.13.0 breaks compatibility with all older middlewares

    Hey @oscarotero,

    Version v0.13.0 of middleware/utils is wreaking havok on previous versions of all your middleware/* packages.

    Here is the issue I am facing.

    I'm using your middleware/whoops package. I'm stuck with v0.4.1 because I'm using http-interop/http-middleware v0.4 in my own middlewares.

    Everything was working flawlessly until you introduced v0.13.0 of middleware/utils.

    The problem:

    v0.13.0 removes "http-interop/http-middleware": "^0.5". https://github.com/middlewares/utils/commit/296dc6129e934ac0db20f279d962cad46226cde3

    Because of this, middleware/whoops v0.4.1 becomes compatible with middleware/utils v0.13.0.

    When I install middleware/whoops v0.4.1, I'm installing middleware/utils v0.13.0, instead of middleware/utils v0.11 (which is the latest compatible version).

    I see 2 possible ways to solve this problem.

    Solution 1:

    • add a conflict section to your composer.json to state that middleware/utils conflicts with "http-interop/http-middleware": "*".

    It's easy, but it will only solve the problem if you remove the v0.13.0 tag from middleware/utils. Not very clean, but possible.

    Solution 2:

    • Go through all your packages, all tags and change the dependency from "middleware/utils": "~0.8" to "middleware/utils": ">=0.8 <0.13"

    It's cleaner but it requires a hell lot more work to solve.

    Whatever solution you choose, I'll be happy to contribute PRs.

    opened by moufmouf 2
  • [#20] zend-diactoros is deprecated by laminas/laminas-diactoros

    [#20] zend-diactoros is deprecated by laminas/laminas-diactoros

    • Updated the composer require-dev section to laminas
    • Updated the Tests to the Laminas namespace
    • Updated the Factory Discovery to the Laminas namespace
    opened by DarkMukke 1
  • Typos in doc block for Guzzle and Slim factories

    Typos in doc block for Guzzle and Slim factories

    https://github.com/middlewares/utils/blob/7ad4e140ea96ba667603ac6a3f5650ccb838f3de/src/Factory/GuzzleFactory.php#L29

    https://github.com/middlewares/utils/blob/7ad4e140ea96ba667603ac6a3f5650ccb838f3de/src/Factory/SlimFactory.php#L30

    opened by partnerizemark 1
  • Error when trying to use an object & method as a handler

    Error when trying to use an object & method as a handler

    I am trying to register a route with fast route using an Object and static method with the following code:

    static public function registerRoute( RouteCollector &$r ): void {
      $r->addRoute(['GET', 'OPTIONS'], '/password', array( self::class, 'renderChallenge') );
    }
    

    instead of the handler being called I instead get the following error message:

    Argument 1 passed to Middlewares\Utils\CallableHandler::__construct() must be callable, object given, called in /src/vendor/middlewares/utils/src/RequestHandlerContainer.php on line 51

    In the course of trying to debug I decided to test if what I was passing was callable using the following:

    // Regular function to check if something is callable
    function isThisCallable( callable $callable  ) {
        call_user_func( $callable );
    }
    
    // Modified code from above
    static public function registerRoutes( RouteCollector &$r ): void {
        $r->addRoute(['GET', 'OPTIONS'], '/password', function() {
           isThisCallable( array(static::class, 'renderChallenge') );
        } );
    }
    

    This test code ran as expected and called the static object's method. Is this a bug or is there another way I should be passing an object and method as the handler?

    opened by mav2287 5
Releases(v3.3.0)
Owner
Middlewares
PSR-15 HTTP Middlewares
Middlewares
PSR-7 and PSR-15 HTTP Basic Authentication Middleware

PSR-7 and PSR-15 Basic Auth Middleware This middleware implements HTTP Basic Authentication. It was originally developed for Slim but can be used with

Mika Tuupola 430 Dec 30, 2022
Static utilitiy classes to bridge PSR-7 http messages to OAuth2 Server requests and responses.

Static utilitiy classes to bridge PSR-7 http messages to OAuth2 Server requests and responses. While this libray is entended for use with Slim 3, it should work with any PSR-7 compatible framework.

Chad Gray 18 Jul 12, 2021
Basic Authentication handler for the JSON API, used for development and debugging purposes

Basic Authentication handler This plugin adds Basic Authentication to a WordPress site. Note that this plugin requires sending your username and passw

WordPress REST API Team 667 Dec 31, 2022
[DEPRECATED] Collection of PSR-7 middlewares

This package is deprecated in favor of the new PSR-15 standard. Check it out here psr7-middlewares Collection of PSR-7 middlewares. Requirements PHP >

Oscar Otero 669 Dec 27, 2022
Learning Management System made in vanilla PHP to learn core concepts and usage of some basic utils

Learning Management System Learning Management System made in vanilla PHP to learn core concepts and usage of some basic utils. Report Bug · Request F

TitansLab 1 Mar 30, 2022
A simple and flexible PHP middleware dispatcher based on PSR-7, PSR-11, and PSR-15

Woohoo Labs. Harmony Woohoo Labs. Harmony is a PSR-15 compatible middleware dispatcher. Harmony was born to be a totally flexible and almost invisible

Woohoo Labs. 153 Sep 5, 2022
A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package.

Net A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package. Features: No hard dependencies; Favours

Minibase 16 Jun 7, 2022
A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package.

Net A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package. Features: No hard dependencies; Favours

Minibase 16 Jun 7, 2022
Builder for stack middlewares based on HttpKernelInterface.

Stack/Builder Builder for stack middlewares based on HttpKernelInterface. Stack/Builder is a small library that helps you construct a nested HttpKerne

null 289 Oct 19, 2022
Sistema de Rotas com Controllers e Middlewares

Sistema de Rotas com Controllers e Middlewares

adev 0 May 30, 2022
🦭 Kirby, but headless only – KQL with bearer token, Express-esque middlewares & more

Kirby Headless Starter ℹ️ Send a Bearer test authorization header with a request to the live playground to test this headless starter. This starter ki

Johann Schopplich 36 Dec 28, 2022
A set of shady Slim Framework middlewares that can solve some annoyances...

Shady A set of shady Slim Framework middlewares that can solve some annoyances... What does it contain? Available middlewares: ApacheVirtualHostFix Ur

Jan-Age Laroo 7 Jun 22, 2021
Open-source library used in Gigadrive projects with common PHP utilities

PHP Commons This library provides PHP utilities used in Gigadrive projects, provided for the open-source community. Functions are registered globally

Gigadrive UG 3 Nov 10, 2021
Middleware for PHP built on top of PSR-7 and PSR-15

zend-stratigility Repository abandoned 2019-12-31 This repository has moved to laminas/laminas-stratigility. From "Strata", Latin for "layer", and "ag

Zend Framework 236 Sep 9, 2022
Fast PSR-7 based routing and dispatch component including PSR-15 middleware, built on top of FastRoute.

Route This package is compliant with PSR-1, PSR-2, PSR-4, PSR-7, PSR-11 and PSR-15. If you notice compliance oversights, please send a patch via pull

The League of Extraordinary Packages 608 Dec 30, 2022
:tada: Release 2.0 is released! Very fast HTTP router for PHP 7.1+ (incl. PHP8 with attributes) based on PSR-7 and PSR-15 with support for annotations and OpenApi (Swagger)

HTTP router for PHP 7.1+ (incl. PHP 8 with attributes) based on PSR-7 and PSR-15 with support for annotations and OpenApi (Swagger) Installation compo

Sunrise // PHP 151 Jan 5, 2023
PSR-6 cache implementation adapting a given PSR-16 instance

PSR-6 cache implementation adapting PSR-16 This package provides a PSR-6 cache instance when you only have a PSR-16 cache at hand. As PSR-6 is more fe

null 1 Oct 15, 2021
PSR Log - This repository holds all interfaces/classes/traits related to PSR-3.

PSR Log This repository holds all interfaces/classes/traits related to PSR-3. Note that this is not a logger of its own. It is merely an interface tha

PHP-FIG 10.1k Jan 3, 2023
PSR-7 and PSR-15 JWT Authentication Middleware

PSR-7 and PSR-15 JWT Authentication Middleware This middleware implements JSON Web Token Authentication. It was originally developed for Slim but can

Mika Tuupola 782 Dec 18, 2022
PSR-7 and PSR-15 HTTP Basic Authentication Middleware

PSR-7 and PSR-15 Basic Auth Middleware This middleware implements HTTP Basic Authentication. It was originally developed for Slim but can be used with

Mika Tuupola 430 Dec 30, 2022