Psr7Middlewares\Middleware::create PHP Method

create() public static method

Create a middleware callable that acts as a "proxy" to a real middleware that must be returned by the given callback.
public static create ( callable | string $basePath, callable $factory = null ) : callable
$basePath callable | string The base path in which the middleware is created (optional)
$factory callable Takes no argument and MUST return a middleware callable or false
return callable
    public static function create($basePath, callable $factory = null)
    {
        if ($factory === null) {
            $factory = $basePath;
            $basePath = '';
        }
        if (!is_callable($factory)) {
            throw new InvalidArgumentException('Invalid callable provided');
        }
        return function (RequestInterface $request, ResponseInterface $response, callable $next) use($basePath, $factory) {
            $path = rtrim($request->getUri()->getPath(), '/');
            $basePath = rtrim($basePath, '/');
            if ($path === $basePath || strpos($path, "{$basePath}/") === 0) {
                $middleware = $factory($request, $response);
            } else {
                $middleware = false;
            }
            if ($middleware === false) {
                return $next($request, $response);
            }
            if (!is_callable($middleware)) {
                throw new RuntimeException(sprintf('Factory returned "%s" instead of a callable or FALSE.', gettype($middleware)));
            }
            return $middleware($request, $response, $next);
        };
    }