A PSR-15 middleware adapter for react/http

Overview

A PSR-15 middleware adapter for react/http

CI status

Wraps PSR-15 middleware into coroutines using RecoilPHP making them usable within react/http as middleware.

Install

To install via Composer, use the command below, it will automatically detect the latest version and bind it with ^.

composer require for/http-middleware-psr15-adapter

Usage

The following usage example uses middlewares/redirect adding one redirect, and using the callback to call several methods on the redirect middleware to change it's behavior:

$loop = Factory::create(); 
$server = new Server([
    /** Other middleware */
    new PSR15Middleware(
        $loop, // The react/event-loop (required) 
        Redirect::class, // String class name of the middleware (required)
        [ // Any constructor arguments (optional)
            ['/old-url' => '/new-url']
        ],
        function ($redirectMiddleware) {
            // This callback is optional, but when used it must return the
            // instance passed into it, or a clone of it.
            return $redirectMiddleware
                ->permanent(false)
                ->query(false)
                ->method(['GET', 'POST'])
            ;
        }
    ),
    /** Other middleware */
]);

Grouped Usage

When using more then one PSR-15 in a row the GroupedPSR15Middleware is more performing than using multiple PSR15Middleware. Consider the following example where we add middlewares/cache for expires headers:

$loop = Factory::create(); 
$server = new Server([
    /** Other middleware */
    (new GroupedPSR15Middleware($loop))->withMiddleware( 
        Redirect::class,
        [
            ['/old-url' => '/new-url']
        ],
        function ($redirectMiddleware) {
            return $redirectMiddleware
                ->permanent(false)
                ->query(false)
                ->method(['GET', 'POST'])
            ;
        }
    )->withMiddleware(Expires::class),
    /** Other middleware */
]);

Warning

This adapter rewrites the code of the PSR-15 middleware during the constructor phase, wrapping all $delegate->process($request) calls into a yield (yield $delegate->process($request)). This should work for most middleware but cannot be guaranteed for all. In case you run into issues please open an issue with the middleware in question you're having problems with.

You might also like...
A lightweight middleware to make api routing session capable.

Laravel stateless session A lightweight middleware to make api routing session capable. Installing $ composer require overtrue/laravel-stateless-sessi

Use middleware to decorate method calls within your application code.
Use middleware to decorate method calls within your application code.

Laravel Middlewarize 🎀 Chain of Responsibility Design Pattern In Laravel Apps 🎀 You can use middlewares to decorate any method calls on any object.

Stepup Middleware - This component is part of "Step-up Authentication as-a Service".

Step-up Middleware This component is part of "Step-up Authentication as-a Service". See Stepup-Deploy for an overview and installation instructions fo

Middleware to provide IP filtering

middlewares/firewall Middleware to provide IP filtering using M6Web/Firewall. Requirements PHP = 7.2 A PSR-7 http library A PSR-15 middleware dispatc

A based PSR-15 microframework that also sets maximum flexibility with minimum complexity and easy replaceability of the individual components, but also of the framework.
A based PSR-15 microframework that also sets maximum flexibility with minimum complexity and easy replaceability of the individual components, but also of the framework.

chubbyphp-framework Description A based PSR-15 microframework that also sets maximum flexibility with minimum complexity and easy replaceability of th

The efficient and elegant, PSR-7 compliant JSON:API 1.1 client library for PHP

Woohoo Labs. Yang Woohoo Labs. Yang is a PHP framework which helps you to communicate with JSON:API servers more easily. Table of Contents Introductio

Tukio is a complete and robust implementation of the PSR-14 Event Dispatcher specification

Tukio is a complete and robust implementation of the PSR-14 Event Dispatcher specification. It supports normal and debug Event Dispatchers, both runtime and compiled Providers, complex ordering of Listeners, and attribute-based registration on PHP 8.

PHP implementation of JSON schema. Fork of the http://jsonschemaphpv.sourceforge.net/ project

JSON Schema for PHP A PHP Implementation for validating JSON Structures against a given Schema with support for Schemas of Draft-3 or Draft-4. Feature

Http-kernel - The HttpKernel component provides a structured process for converting a Request into a Response.

HttpKernel Component The HttpKernel component provides a structured process for converting a Request into a Response by making use of the EventDispatc

Comments
  • Update example in readme

    Update example in readme

    The package has a dependency of "react/http": "^0.8.0", so we can simply pass an array of middleware to Server constructor. There is no need to explicitly create an instance of MiddlewareRunner.

    opened by seregazhuk 5
  • Error with Redirect middleware

    Error with Redirect middleware

    I've tried your example from Readme as it is. Here is the code:

    $loop = Factory::create();
    $server = new Server([
        new PSR15Middleware(
            $loop,
            \Middlewares\Redirect::class,
            [
                ['/old-url' => '/new-url']
            ],
            function ($redirectMiddleware) {
                return $redirectMiddleware
                    ->permanent(false)
                    ->query(false)
                    ->method(['GET', 'POST']);
            }
        ),
        function(\Psr\Http\Message\RequestInterface $request){
            return new \React\Http\Response(200);
        }
    ]);
    
    
    $socket = new \React\Socket\Server('127.0.0.1:8000', $loop);
    $server->listen($socket);
    
    echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL;
    $loop->run();
    

    But when trying to request http://127.0.0.1:8000/old-url I receive 500, and the server script is running and reports nothing to the console. Also the same is true for GroupedPSR15Middleware. Can you suggest any ways to debug it?

    opened by seregazhuk 4
  • A release.

    A release.

    Readme installation fails.

    $ composer require for/http-middleware-psr15-adapter
      [InvalidArgumentException]  Could not find a matching version of package for/http-middleware-psr15-adapter. Check the package spelling, your version constraint and that the package is available in a stability which matches your minimum-stability (stable).
    
    opened by bweston92 3
  • Replace magic __DIR__ and __FILE__ constants with a string representing the original __DIR__ and __FILE__

    Replace magic __DIR__ and __FILE__ constants with a string representing the original __DIR__ and __FILE__

    Fixes / Closes #4

    Ran into this issue when using a middleware that relies on those magic constants. It couldn't find the file it was looking for because __DIR__ and __FILE__ where now the ones for YieldingMiddlewareFactory.

    opened by WyriHaximus 0
Releases(v2.0.0)
Owner
Friends of ReactPHP
Friends of @ReactPHP
Friends of ReactPHP
PSR-7 middleware foundation for building and dispatching middleware pipelines

laminas-stratigility From "Strata", Latin for "layer", and "agility". This package supersedes and replaces phly/conduit. Stratigility is a port of Sen

Laminas Project 47 Dec 22, 2022
OpenAPI(v3) Validators for Symfony http-foundation, using `league/openapi-psr7-validator` and `symfony/psr-http-message-bridge`.

openapi-http-foundation-validator OpenAPI(v3) Validators for Symfony http-foundation, using league/openapi-psr7-validator and symfony/psr-http-message

n1215 2 Nov 19, 2021
Disable Google's FLoC with help of PSR-15 middleware

Disable Google's FLoC with PSR-15 middleware This package will help you disable Google's FLoC. Installation You can install the package via composer:

P7V 9 Dec 14, 2022
PSR-15 middleware to geolocate the client using the ip address

middlewares/geolocation ![SensioLabs Insight][ico-sensiolabs] Middleware to geolocate the client using the ip address and Geocoder and save the result

Middlewares 10 Mar 22, 2022
PSR-15 middleware to use Whoops as error handler

middlewares/whoops Middleware to use Whoops as error handler. Requirements PHP >= 7.2 A PSR-7 http library A PSR-15 middleware dispatcher Installation

Middlewares 31 Jun 23, 2022
A PSR-15 middleware to handle content negotiation

Content negotiation middleware Motivation Packages like middlewares/negotiation do a very good job to detect the correct content type based on the Acc

Luís Cobucci 47 Nov 16, 2022
PSR-15 compatible middleware for Whoops, the pretty error handler

PSR-15 middleware for Whoops A PSR-15 compatible middleware for Whoops, the fantastic pretty error handler for PHP. Installation You can install the l

Franz Liedke 25 May 20, 2022
An internal redirect mechanism for PSR-15 middleware stacks

HTTP Request Forwarder The aim of this library is to make it possible to pass the HTTP request to another handler, creating a so-called internal redir

Zoltan Kovago 0 Jul 27, 2022
It validates PSR-7 messages (HTTP request/response) against OpenAPI specifications

OpenAPI PSR-7 Message (HTTP Request/Response) Validator This package can validate PSR-7 messages against OpenAPI (3.0.x) specifications expressed in Y

The League of Extraordinary Packages 421 Jan 3, 2023
Provides a Middleware to integration Tideways into Symfony Messenger Processing

Tideways Middleware for Symfony Messenger This package is currently under development and might be moved into the Tideways PHP Extension or stay indep

Tideways 6 Jul 5, 2022