Filters ResponseContext from common HTTP errors

@param ResponseContextAbstract $responseContext

@throws BadResponseContextException
@throws InvalidResponseContent
775062
protected function processApiResponseContextErrors(ResponseContextAbstract $responseContext): void
    {
        $responseArray = $responseContext->getArray();

        $this->filterYandexSpecificErrors($responseArray);

        parent::processApiResponseContextErrors($responseContext);

        if (empty($responseArray['text'])) {
            throw new InvalidResponseContent(sprintf('There is no required field "%s" in response', 'text'));
        }
    }
870022
public function setContent(string $content = null): ResponseContextAbstract
    {
        if (is_null($content)) {
            return $this;
        }

        $this->assertIsValid($content);

        $this->content = $content;

        return $this;
    }
404721
protected function prepareCheckTextsResponse(ResponseContextAbstract $context): SpellCheckResponse
    {
        $response = new SpellCheckResponse();

        $corrections = [];

        foreach ($context->getArray() as $wordCorrections) {
            $corrected = [];

            foreach ($wordCorrections as $wordCorrection) {
                if (!empty($wordCorrection['s']) && !empty($wordCorrection['word'])) {
                    $corrected[$wordCorrection['word']] = (array)$wordCorrection['s'];
                }
            }

            $corrections[] = $corrected;
        }

        $response->setCorrections($corrections);

        return $response;
    }
277693
protected function processResponse(
        RequestInterface $request,
        PsrRequestInterface $clientRequest,
        PsrResponseInterface $clientResponse
    ): ResponseInterface {
        $endpoint = $this->endpointService->getEndpointForRequest($request);
        $responseContents = $this->getContentsFromMessage($clientResponse);

        try {
            $result = $this->serializer->deserialize($responseContents, $endpoint->getResponseClass(), 'json');
        } catch (Exception $e) {
            $requestContents = $this->getContentsFromMessage($clientRequest);
            throw new InvalidResponseException($e->getMessage(), $requestContents, $responseContents, $e);
        }

        return $result;
    }
356305
public function handleNotFound(ServerRequestInterface $request, ResponseInterface $response)
    {
        return $this
            ->getContentTypeHandler($request)
            ->handleNotFound($request, $response);
    }
66483
protected function _actionValidate($context)
    {
        $data = $context->data;
        $key = $data->key;
        $value = $data->value;
        $method = 'validate'.ucfirst($key);
        $result = true;
        $result = $this->getValidator()->$method($value);
        $output = $this->getValidator()->getMessage();

        if ($result === false) {
            $context->response->status = AnHttpResponse::PRECONDITION_FAILED;

            if (is_string($output)) {
                $output = array('errorMsg' => $output);
            }

            $context->response->validation = json_encode($output);
        } else {
            $context->response->validation = json_encode($output);
        }
    }
1346630
public function transform(ApiRequest $request, ApiResponse $response, array $context = []): ApiResponse
	{
		// Return immediately if context hasn't defined renderer
		if (!isset($context['renderer'])) return $response;

		// Fetch service
		$service = $this->container->getByType($context['renderer'], false);

		if (!$service) {
			throw new InvalidStateException(sprintf('Renderer "%s" is not registered in container', $context['renderer']));
		}

		if (!is_callable($service)) {
			throw new InvalidStateException(sprintf('Renderer "%s" must implement __invoke() method', $context['renderer']));
		}

		return $service($request, $response, $context);
	}
533835
public function isValid($context = null)
    {
        // When there's an invalid data type, it should immediately report as invalid.
        if ($this->invalidDataTypeException !== null) {
            return false;
        }

        // When there's no data and the filter itself is not required,
        // it should immediately report as valid.
        if (!$this->data && !$this->isRequired()) {
            return true;
        }

        // Don't filter at all when "inputsToFilter" is set to empty array
        if (!$this->needsFiltering()) {
            return true;
        }

        return parent::isValid($context);
    }
329567
public function parse( Request $request, Response $response )
    {
        $error = parent::parse( $request, $response );

        if ( $error )
        {
            return $error;
        }

        $method = null;
        $params = xmlrpc_decode_request(
            $request->getContent(),
            $method,
            'utf-8'
        );

        if ( ! $params )
        {
            return self::PARSE;
        }

        if ( empty( $method ) || empty( $params ) )
        {
            return self::INVALID_REQUEST;
        }

        $this->method   = $method;
        $this->params   = $params;

        return null;
    }
580883
protected function collectConflictsWithin(ComparisonContext $context): void
    {
        // A field map is a keyed collection, where each key represents a response
        // name and the value at that key is a list of all fields which provide that
        // response name. For every response name, if there are multiple fields, they
        // must be compared to find a potential conflict.
        foreach ($context->getFieldMap() as $responseName => $fields) {
            $fieldsCount = \count($fields);

            // This compares every field in the list to every other field in this list
            // (except to itself). If the list only has one item, nothing needs to
            // be compared.
            if ($fieldsCount > 1) {
                /** @noinspection ForeachInvariantsInspection */
                for ($i = 0; $i < $fieldsCount; $i++) {
                    for ($j = $i + 1; $j < $fieldsCount; $j++) {
                        $conflict = $this->findConflict(
                            $responseName,
                            $fields[$i],
                            $fields[$j],
                            // within one collection is never mutually exclusive
                            false/* $areMutuallyExclusive */
                        );

                        if (null !== $conflict) {
                            $context->reportConflict($conflict);
                        }
                    }
                }
            }
        }
    }
1164519
public function filterYandexSpecificErrors(array $responseArray): void
    {
        if (isset($responseArray['code'])) {
            if (($responseArray['code'] !== YandexApiStatusesInterface::STATUS_SUCCESS) &&
                isset(self::$customStatusMessages[$responseArray['code']])
            ) {
                $errorMessage = $responseArray['message']
                    ?? self::$customStatusMessages[$responseArray['code']];

                throw new BadResponseContextException($errorMessage, $responseArray['code']);
            }
        }
    }
1060669
@Override
    public void filter(ClientRequestContext requestContext) {
        //
        if (requestContext == null || jwt == null || requestContext.getHeaders().containsKey("Authorization")) {
            return;
        }
        if (header == null || header.equals("")) {
            header = "Authorization";
        }
        final String headerValue;
        if ("Authorization".equals(header)) {
            headerValue = "Bearer " + jwt;
        } else {
            headerValue = jwt;
        }

        requestContext.getHeaders().add(header, headerValue);
    }
1218272
public function execute($actionContext) {
        $response = $actionContext->getHttpContext()->getResponse();
        $response->setStatusCode($this->statusCode);
        $response->setStatusDescription($this->statusDescription);
        $response->write($result);
        $response->end();
    }
113554
public function route(RequestInterface $request, ResponseInterface $response, Context $context = null)
    {
        $this->level++;

        $this->eventDispatcher->dispatch(Event::REQUEST_INCOMING, new RequestIncomingEvent($request));

        // load controller
        if ($context === null) {
            $factory = $this->config->get('psx_context_factory');
            if ($factory instanceof \Closure) {
                $context = $factory();
            } else {
                $context = new Context();
            }
        }

        try {
            $this->loader->load($request, $response, $context);
        } catch (StatusCode\NotModifiedException $e) {
            $response->setStatus($e->getStatusCode());
            $response->setBody(new StringStream());
        } catch (StatusCode\RedirectionException $e) {
            $response->setStatus($e->getStatusCode());
            $response->setHeader('Location', $e->getLocation());
            $response->setBody(new StringStream());
        } catch (\Throwable $e) {
            $this->eventDispatcher->dispatch(Event::EXCEPTION_THROWN, new ExceptionThrownEvent($e, new ControllerContext($request, $response)));

            $this->handleException($e, $response);

            try {
                $context->setException($e);

                $class      = isset($this->config['psx_error_controller']) ? $this->config['psx_error_controller'] : ErrorController::class;
                $controller = $this->controllerFactory->getController($class, $context);

                $this->loader->execute($controller, $request, $response);
            } catch (\Throwable $e) {
                // in this case the error controller has thrown an exception.
                // This can happen i.e. if we can not represent the error in an
                // fitting media type. In this case we send json to the client

                $this->handleException($e, $response);

                $record = $this->exceptionConverter->convert($e);

                $response->setHeader('Content-Type', 'application/json');
                $response->setBody(new StringStream(Parser::encode($record, JSON_PRETTY_PRINT)));
            }
        }

        // for HEAD requests we never return a response body
        if ($request->getMethod() == 'HEAD') {
            $response->setHeader('Content-Length', $response->getBody()->getSize());
            $response->setBody(new StringStream(''));
        }

        $this->eventDispatcher->dispatch(Event::RESPONSE_SEND, new ResponseSendEvent($response));

        $this->level--;

        return $response;
    }
150746
public function setContext(RequestContext $context)
    {
        foreach ($this->matchers as $matcher) {
            $matcher->setContext($context);
        }

        $this->context = $context;
    }
372605
protected function failedAction(Context $context)
    {
        $input = function () use ($context) {
            return [$context];
        };

        return $this->newInstance(
            $input,
            [$this->matcher, 'getName'],
            $this->failResponder
        );
    }
1267401
protected function _actionEdit(ControllerContext $context)
    {
        $entities = $context->entity;

        if(count($entities))
        {
            foreach($entities as $entity) {
                $entity->setProperties($context->request->data->toArray());
            }

            //Only set the reset content status if the action explicitly succeeded
            if($entities->save() === true) {
                $context->response->setStatus(HttpResponse::RESET_CONTENT);
            }
        }
        else throw new ControllerExceptionResourceNotFound('Resource could not be found');

        return $entities;
    }