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);
        };
    }