Perform content negotiation.

@param HttpFactoryInterface $httpFactory
@param ServerRequestInterface $request
@param CodecMatcherInterface $codecMatcher
@throws JsonApiException
@see http://jsonapi.org/format/#content-negotiation
501919
protected function doContentNegotiation(
        HttpFactoryInterface $httpFactory,
        ServerRequestInterface $request,
        CodecMatcherInterface $codecMatcher
    ) {
        $parser = $httpFactory->createHeaderParametersParser();
        $checker = $httpFactory->createHeadersChecker($codecMatcher);

        $checker->checkHeaders($parser->parse($request, http_contains_body($request)));
    }
461596
public function visit(
        CommandInterface $command,
        RequestInterface $request,
        Parameter $param
    ) {
        $this->jsonData[$param->getWireName()] = $this->prepareValue(
            $command[$param->getName()],
            $param
        );

        return $request->withBody(Psr7\stream_for(\GuzzleHttp\json_encode($this->jsonData)));
    }
318985
private function requestUrlMatchesExpectation(ServerRequestInterface $httpRequest, Request $expectedRequest)
    {
        $inputSource = $this->inputSourceFactory->createFromConfig([
            'url' => null,
        ]);
        $matcher = $this->matcherFactory->createFromConfig([
            $expectedRequest->getUrl()->getMatcher() => $expectedRequest->getUrl()->getValue(),
        ]);

        return $this->evaluate($inputSource, $matcher, $httpRequest);
    }
854680
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = (new ResponseFactory)->createResponse();

        $analyzer = CorsAnalyzer::instance($this->buildSettings($request, $response));
        if ($this->logger) {
            $analyzer->setLogger($this->logger);
        }
        $cors = $analyzer->analyze($request);

        switch ($cors->getRequestType()) {
            case CorsAnalysisResultInterface::ERR_ORIGIN_NOT_ALLOWED:
                $response = $response->withStatus(401);
                return $this->processError($request, $response, [
                    "message" => "CORS request origin is not allowed.",
                ]);
            case CorsAnalysisResultInterface::ERR_METHOD_NOT_SUPPORTED:
                $response = $response->withStatus(401);
                return $this->processError($request, $response, [
                    "message" => "CORS requested method is not supported.",
                ]);
            case CorsAnalysisResultInterface::ERR_HEADERS_NOT_SUPPORTED:
                $response = $response->withStatus(401);
                return $this->processError($request, $response, [
                    "message" => "CORS requested header is not allowed.",
                ]);
            case CorsAnalysisResultInterface::TYPE_PRE_FLIGHT_REQUEST:
                $cors_headers = $cors->getResponseHeaders();
                foreach ($cors_headers as $header => $value) {
                    /* Diactoros errors on integer values. */
                    if (false === is_array($value)) {
                        $value = (string)$value;
                    }
                    $response = $response->withHeader($header, $value);
                }
                return $response->withStatus(200);
            case CorsAnalysisResultInterface::TYPE_REQUEST_OUT_OF_CORS_SCOPE:
                return $handler->handle($request);
            default:
                /* Actual CORS request. */
                $response = $handler->handle($request);
                $cors_headers = $cors->getResponseHeaders();
                foreach ($cors_headers as $header => $value) {
                    /* Diactoros errors on integer values. */
                    if (false === is_array($value)) {
                        $value = (string)$value;
                    }
                    $response = $response->withHeader($header, $value);
                }
                return $response;
        }
    }
215195
protected void sendClientRequest(HttpMessage request) {
        BuilderSupport<HttpActionBuilder> action = builder -> {
            HttpClientActionBuilder.HttpClientSendActionBuilder sendBuilder = builder.client(httpClient).send();
            HttpClientRequestActionBuilder requestBuilder;

            if (request.getRequestMethod() == null || request.getRequestMethod().equals(HttpMethod.POST)) {
                requestBuilder = sendBuilder.post().message(request);
            } else if (request.getRequestMethod().equals(HttpMethod.GET)) {
                requestBuilder = sendBuilder.get().message(request);
            } else if (request.getRequestMethod().equals(HttpMethod.PUT)) {
                requestBuilder = sendBuilder.put().message(request);
            } else if (request.getRequestMethod().equals(HttpMethod.DELETE)) {
                requestBuilder = sendBuilder.delete().message(request);
            } else if (request.getRequestMethod().equals(HttpMethod.HEAD)) {
                requestBuilder = sendBuilder.head().message(request);
            } else if (request.getRequestMethod().equals(HttpMethod.TRACE)) {
                requestBuilder = sendBuilder.trace().message(request);
            } else if (request.getRequestMethod().equals(HttpMethod.PATCH)) {
                requestBuilder = sendBuilder.patch().message(request);
            } else if (request.getRequestMethod().equals(HttpMethod.OPTIONS)) {
                requestBuilder = sendBuilder.options().message(request);
            } else {
                requestBuilder = sendBuilder.post().message(request);
            }

            if (StringUtils.hasText(url)) {
                requestBuilder.uri(url);
            }
        };

        runner.http(action);
    }
659063
private function createRequest(
        SapiInterface $sapi,
        PsrContainerInterface $container,
        callable $requestFactory
    ): ServerRequestInterface {
        // check the factory method signature
        assert(
            $this->checkPublicStaticCallable(
                $requestFactory,
                [SapiInterface::class, PsrContainerInterface::class],
                ServerRequestInterface::class
            ),
            'Factory method should have signature ' .
            '`public static methodName(SapiInterface, PsrContainerInterface): ServerRequestInterface`'
        );

        $request = call_user_func($requestFactory, $sapi, $container);

        return $request;
    }
841290
protected void receiveServerRequest(HttpMessage request) {
        BuilderSupport<HttpActionBuilder> action = builder -> {
            HttpServerActionBuilder.HttpServerReceiveActionBuilder receiveBuilder = builder.server(httpServer).receive();
            HttpServerRequestActionBuilder requestBuilder;

            if (request.getRequestMethod() == null || request.getRequestMethod().equals(HttpMethod.POST)) {
                requestBuilder = receiveBuilder.post().message(request);
            } else if (request.getRequestMethod().equals(HttpMethod.GET)) {
                requestBuilder = receiveBuilder.get().message(request);
            } else if (request.getRequestMethod().equals(HttpMethod.PUT)) {
                requestBuilder = receiveBuilder.put().message(request);
            } else if (request.getRequestMethod().equals(HttpMethod.DELETE)) {
                requestBuilder = receiveBuilder.delete().message(request);
            } else if (request.getRequestMethod().equals(HttpMethod.HEAD)) {
                requestBuilder = receiveBuilder.head().message(request);
            } else if (request.getRequestMethod().equals(HttpMethod.TRACE)) {
                requestBuilder = receiveBuilder.trace().message(request);
            } else if (request.getRequestMethod().equals(HttpMethod.PATCH)) {
                requestBuilder = receiveBuilder.patch().message(request);
            } else if (request.getRequestMethod().equals(HttpMethod.OPTIONS)) {
                requestBuilder = receiveBuilder.options().message(request);
            } else {
                requestBuilder = receiveBuilder.post().message(request);
            }

            for (Map.Entry<String, String> headerEntry : pathValidations.entrySet()) {
                requestBuilder.validate(headerEntry.getKey(), headerEntry.getValue());
            }
            pathValidations.clear();
        };

        runner.http(action);
    }
1374389
private function createUri(HTTPServerFactory $httpFactory, array $server) : UriInterface {
		$uri = $httpFactory->createUri();

		$uri = $this->withScheme($uri, $server);
		$uri = $this->withHost($uri, $server);
		$uri = $this->withServerPort($uri, $server);
		$uri = $this->withPath($uri, $server);
		$uri = $this->withQueryString($uri, $server);

		return $uri;
	}
309514
public final HttpServer httpRequestDecoder(Function<HttpRequestDecoderSpec, HttpRequestDecoderSpec> requestDecoderOptions) {
		return tcpConfiguration(
				requestDecoderOptions.apply(new HttpRequestDecoderSpec())
				                     .build());
	}
60823
private function requestMethodMatchesExpectation(ServerRequestInterface $httpRequest, RequestConditions $expectedRequest)
    {
        $inputSource = $this->inputSourceLocator->locate(InputSources::METHOD);
        $matcher = $this->matcherLocator->locate(Matchers::SAME_STRING);

        return $matcher->match(
            $inputSource->getValue($httpRequest),
            $expectedRequest->getMethod()->asString()
        );
    }
461109
public function execute(RequestInterface $request): RequestInterface
    {
        if ($request->getUri()->getPath() === self::ENDPOINT_INSTALLATION) {
            return $request;
        } else {
            $signature = $this->determineRequestSignature(
                $request->getUri(),
                $request->getMethod(),
                $request->getBody()->getContents(),
                $request->getHeaders()
            );

            return $request->withHeader(self::HEADER_CLIENT_SIGNATURE, $signature);
        }
    }
1353586
public function sendApiRest($code=200, $jsonString= '', $contentType='application/json'){
        $this->setStatusCode($code);
        $this->setContentType($contentType);
        $this->setContent($jsonString);
        $this->sendContent();
    }
1235110
public function getOptions(ServerRequestInterface $request): void
    {
        parent::getOptions($request);

        $this->search  = $request->get('search', '');
        $this->replace = $request->get('replace', '');
        $this->method  = $request->get('method', 'exact');
        $this->case    = $request->get('case', '');

        $this->error = '';
        switch ($this->method) {
            case 'exact':
                $this->regex = preg_quote($this->search, '/');
                break;
            case 'words':
                $this->regex = '\b' . preg_quote($this->search, '/') . '\b';
                break;
            case 'wildcards':
                $this->regex = '\b' . str_replace([
                        '\*',
                        '\?',
                    ], [
                        '.*',
                        '.',
                    ], preg_quote($this->search, '/')) . '\b';
                break;
            case 'regex':
                $this->regex = $this->search;
                // Check for invalid regular expressions.
                // A valid regex on an empty string returns zero.
                // An invalid regex on an empty string returns false and throws a warning.
                try {
                    preg_match('/' . $this->search . '/', '');
                } catch (Throwable $ex) {
                    /* I18N: http://en.wikipedia.org/wiki/Regular_expression */
                    $this->error = '<div class="alert alert-danger">' . I18N::translate('The regular expression appears to contain an error. It can’t be used.') . '</div>';
                }
                break;
        }
    }
1261384
private function detectFromHeader(ServerRequestInterface $request)
    {
        $headers = call_user_func_array('array_merge', array_column($this->formats, 'mime-type'));
        $accept = $request->getHeaderLine('Accept');
        $mime = $this->negotiateHeader($accept, new Negotiator(), $headers);

        if ($mime !== null) {
            foreach ($this->formats as $format => $data) {
                if (in_array($mime, $data['mime-type'], true)) {
                    return $format;
                }
            }
        }
    }
1328009
public function match(ServerRequestInterface $request) : RouterMatch
    {
        $path = $request->getUri()->getPath();
        $syContext = new RequestContext('/');
        $syMatcher = new UrlMatcher($this->syRouteCollection, $syContext);
        try {
            $params = $syMatcher->match($path);
        } catch (\Throwable $e) {
            throw new HttpException(404, "No route matched for path $path",
                null, $e);
        }
        
        $matchedRouteName = $params['_route'];
        unset($params['_route']);
        $route = $this->routeProvider->getRouteFromName($matchedRouteName);
        $routerMatch = new RouterMatch($route, $params);
        return $routerMatch;
    }
32417
protected function sendRequest(RequestInterface $request)
    {
        try {
            $response = $this->httpClient->send(
                $request,
                $this->getRequestOptions()
            );

            $this->multipartResources = [];

            return json_decode($response->getBody());
        } catch (RequestException $e) {
            $this->throwRequestException($e);
        }
    }
1273753
public function process(ServerRequestInterface $request, DelegateInterface $delegate)
    {
        $contentType = $request->getHeaderLine('Content-Type');

        if (!$this->match($contentType)) {
            return $delegate->process($request);
        }

        $rawBody = (string)$request->getBody();
        $parsedBody = json_decode($rawBody, true);

        if (!empty($rawBody) && json_last_error() !== JSON_ERROR_NONE) {
            $statusCode = 400;
            $apiMessage = new HttpStatusCodeApiMessage($statusCode);
            $apiMessage->setCode('invalid-json');
            $apiMessage->setValue('Invalid JSON');
            $apiResponse = $this->newPsrResponseWithTranslatedMessages->__invoke(
                null,
                $statusCode,
                $apiMessage
            );

            return $apiResponse;
        }

        $request = $request
            ->withAttribute('rawBody', $rawBody)
            ->withParsedBody($parsedBody);

        return $delegate->process($request);
    }