Giter Site home page Giter Site logo

utils's Introduction

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.

utils's People

Contributors

ecolinet avatar eusonlito avatar fenric avatar filisko avatar maspeng avatar mekdrop avatar mikespub avatar moufmouf avatar oscarotero avatar sagikazarmark avatar sevavietl avatar shadowhand avatar solcik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

utils's Issues

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" .
296dc61

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.

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".

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.

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?

Add support for psr/http-message 2.x

When you require middlewares/utils 3.3.0 e.g. to use the dispatcher, it also forces your project to remain with psr/http-message 1.x even when you don't use the factory methods here.

Updated with PR #27

Support PHP 8

Tests seem to pass but dev dependencies need to be reviewed

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',
];

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.