private function setCORSheaders($request, $response, $next)
    {
        $settings = new Settings();
        $settings->setServerOrigin([
            'scheme' => $request->getUri()->getScheme(),
            'host'   => $request->getUri()->getHost(),
            'port'   => $request->getUri()->getPort(),
        ])
        ->setRequestCredentialsSupported(true)
        ->setPreFlightCacheMaxAge(86400)
        ->setRequestAllowedMethods(['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'])
        ->setRequestAllowedHeaders(['X-Requested-With']);
        
        $httpOrigin = $request->getHeader('HTTP_ORIGIN');
        if (count($httpOrigin)) {
            $settings->setServerOrigin($httpOrigin[0]);
        }

        if ($request->getHeader('HTTP_ACCESS_CONTROL_REQUEST_METHOD')) {
            $settings->setRequestAllowedMethods($request->getHeader('HTTP_ACCESS_CONTROL_REQUEST_METHOD'));
        }

        if ($request->getHeader('HTTP_ACCESS_CONTROL_REQUEST_HEADERS')) {
            $settings->setRequestAllowedHeaders($request->getHeader('HTTP_ACCESS_CONTROL_REQUEST_HEADERS'));
        }

        $cors = Analyzer::instance($settings)->analyze($request);
        switch ($cors->getRequestType()) {
            case AnalysisResultInterface::ERR_NO_HOST_HEADER:
            case AnalysisResultInterface::ERR_ORIGIN_NOT_ALLOWED:
            case AnalysisResultInterface::ERR_METHOD_NOT_SUPPORTED:
            case AnalysisResultInterface::ERR_HEADERS_NOT_SUPPORTED:
                return $response->withStatus(403);
            case AnalysisResultInterface::TYPE_REQUEST_OUT_OF_CORS_SCOPE:
                return $next($request, $response);
            case AnalysisResultInterface::TYPE_PRE_FLIGHT_REQUEST:
                foreach ($cors->getResponseHeaders() as $name => $value) {
                    $response = $response->withHeader($name, $value);
                }
                return $response->withStatus(200);
            default:
                $response = $next($request, $response);
                foreach ($cors->getResponseHeaders() as $name => $value) {
                    $response = $response->withHeader($name, $value);
                }
                return $response;
        }
    }