Process the response and decode it.

@param   Response  $response      The response.
@param   integer   $expectedCode  The expected "good" code.

@return  mixed

@since   1.0
@throws  \DomainException
511854
protected function processResponse(Response $response, $expectedCode = 200)
	{
		// Validate the response code.
		if ($response->code != $expectedCode)
		{
			// Decode the error response and throw an exception.
			$error = json_decode($response->body);
			$message = isset($error->message) ? $error->message : 'Invalid response received from GitHub.';
			throw new \DomainException($message, $response->code);
		}

		return json_decode($response->body);
	}
853772
public function handleResponse($response) {

        // No filter has been applied to this request.
        // Standard request, instantiate a single object.
        if(empty($this->filter)) {
            return $this->instantiateEntity($response);
        }

        // Filter applied.
        // Instantiate an object for each result returned.
        else {
            return array_map(function ($object) {
                return $this->instantiateEntity($object);
            }, $response->data);
        }

    }
1046651
protected function handleErrors(ResponseInterface $response)
    {
        switch ($response->getStatusCode()) {
            case 401:
                throw new DomainExceptions\InvalidApiKeyException('Invalid API key');
                break;
            case 403:
                throw new DomainExceptions\InsufficientPrivilegesException('Insufficient Privileges');
                break;
            case 404:
                throw new DomainExceptions\NotFoundException('Not found');
                break;
            case 422:
                throw new DomainExceptions\UnprocessableEntityException('Unprocessable entity');
            case 429:
                throw new DomainExceptions\RateLimitExceededException('Rate limit exceeded');
            default:
                throw new DomainExceptions\UnknownErrorException('Unknown error');
                break;
        }
    }
314343
public function execute(Request $request, Response $response, ...$params)
    {
        if (is_string($this->_params[0])) {
            $response->write(...$this->_params);
        } elseif (is_callable($this->_params[0])) {
            $this->_params[0]($request, $response);
        } else {
            throw new \DomainException('INVALID_ROUTER_FUNC');
        }
    }
434345
protected function handleErrors(ResponseInterface $response)
    {
        $body = $response->getBody()->__toString();

        $content = json_decode($body, true);
        $message = '';
        if (JSON_ERROR_NONE === json_last_error()) {
            $message = $content['error'];
        }

        switch ($response->getStatusCode()) {
            case 401:
                throw new DomainExceptions\InvalidApiKeyException($message);
                break;
            case 403:
                throw new DomainExceptions\InsufficientPrivilegesException($message);
                break;
            case 404:
                throw new DomainExceptions\NotFoundException($message);
                break;

            default:
                throw new DomainExceptions\UnknownErrorException($message);
                break;
        }
    }
1297902
private function handleException($e)
    {
        // TODO: test coverage
        if ($e instanceof ClientException) {
            // will catch all 4xx errors
            if ($e->getResponse()->getStatusCode() == 403) {
                throw new AuthenticationException(
                    $this->apiKey,
                    $this->apiSecret,
                    null,
                    $e
                );
            } else {
                throw new DomainException(
                    'The OpenTok API request failed: '. json_decode($e->getResponse()->getBody(true))->message,
                    null,
                    $e
                );
            }
        } else if ($e instanceof ServerException) {
            // will catch all 5xx errors
            throw new UnexpectedValueException(
                'The OpenTok API server responded with an error: ' . json_decode($e->getResponse()->getBody(true))->message,
                null,
                $e
            );
        } else {
            // TODO: check if this works because Exception is an interface not a class
            throw new \Exception('An unexpected error occurred');
        }
    }
717661
private function processResponse(ResponseInterface $response)
    {
        if (200 !== $response->getStatusCode()) {
            throw new \RuntimeException('Query to the API server did not result in an appropriate response code');
        }

        $body = guzzle_json_decode((string) $response->getBody(), true);

        if ('OK' !== $body['error']) {
            throw new \RuntimeException('Query to the API server did not result in an appropriate response code');
        }

        return $body;
    }
1358918
private function _parseResponse(Response $response)
    {
        switch ($this->_format) {
            case self::FORMAT_JSON:
                return json_decode($response, $this->_isJsonDecodeAssoc);
                break;
            default:
                return $response;
        }
    }
638787
public function response(Response $response, CryptographyEngine $cryptographyEngine)
	{
		$decryptedResponse = new DecryptedCommandResponse($response);

		$decryptedResponse->assignCryptographyEngine($cryptographyEngine, $this->email);

		return $decryptedResponse;
	}
974452
protected function parseResponse($response)
    {
        $result = json_decode((string) $response->getBody(), true);

        if (isset($result['exception'])) {
            throw (new DelegationException($result['message']))->setException($result['exception']);
        }

        return $result;
    }
1187998
protected function decode_response($response) {
        // XMLRPC server in Moodle encodes response using function xmlrpc_encode_request() with method==null
        // see {@link webservice_xmlrpc_server::prepare_response()} . We should use xmlrpc_decode_request() for decoding too.
        $method = null;
        $encoding = null;
        if (preg_match('/^<\?xml version="1.0" encoding="([^"]*)"\?>/', $response, $matches)) {
            // Sometimes xmlrpc_decode_request() fails to recognise encoding, let's help it.
            $encoding = $matches[1];
        }
        $r = xmlrpc_decode_request($response, $method, $encoding);
        return $r;
    }
468853
protected function checkResponse(Response $response)
    {
        $status = $response->getStatusCode();
        $reason = $response->getReasonPhrase();
        switch ($status) {
            case '403':
                throw new Exceptions\GeocodioAuthError($reason);
                break;

            case '422':
                throw new Exceptions\GeocodioDataError($reason);
                break;

            case '500':
                throw new Exceptions\GeocodioServerError($reason);
                break;

            case '200':
                return $response;
                break;

            default:
                throw new Exceptions\GeocodioException("There was a problem with your request - $reason");
                break;
        }
    }
1152606
private function checkErrorResponse(ResponseInterface $response)
    {
        if ($response->getStatusCode() >= 500) {
            $errors = json_decode($response->getBody()->__toString(), true)['details'];

            throw new \RuntimeException(
                'An error occurred creating the expectation: '
                . ($errors ? var_export($errors, true) : '')
                . $response->getBody()->__toString());
        }

        if ($response->getStatusCode() >= 400) {
            throw new \RuntimeException('Request error while creating the expectation');
        }
    }
519793
protected function toResponse($response, int $statusCode = 200): ResponseContract
    {
        if ($response instanceof JsonResponse) {
            $data = $response->getData(true);
            $statusCode = $response->getStatusCode();
        } elseif ($response instanceof Arrayable || $response instanceof Model) {
            $data = $response->toArray();
        } elseif (is_array($response)) {
            $data = $response;
        } elseif ($response instanceof ArrayObject) {
            // @todo 待验证
            $data = (array) $response;
        } else {
            throw new DomainException('The response type error');
        }

        /* @var ResponseContract $response */
        $response = $this->app->make('response');
        $response->setStatusCode($statusCode);

        return $data ? $response->setData($data)->setPackData(
            $this->app->make('bridging.packer')->pack($data)
        ) : $response;
    }
1248733
public function validateResponse($url, $response)
	{
		if (!$code = $this->getOption('success_code'))
		{
			$code = 200;
		}

		if (strpos($url, '::(~)') === false && $response->code != $code)
		{
			if ($error = json_decode($response->body))
			{
				throw new \DomainException('Error code ' . $error->errorCode . ' received with message: ' . $error->message . '.');
			}

			throw new \DomainException($response->body);
		}
	}
578893
public function readValue($token = null, $expectedType = null)
    {
        if ($token === null) {
            $token = $this->tokenizer->getNextToken();
        }

        if ($token === false) {
            if ($expectedType !== null) {
                throw new Type\PdfTypeException('Got unexpected token type.', Type\PdfTypeException::INVALID_DATA_TYPE);
            }
            return false;
        }

        switch ($token) {
            case '(':
                $this->ensureExpectedType($token, $expectedType);
                return PdfString::parse($this->streamReader);

            case '<':
                if ($this->streamReader->getByte() === '<') {
                    $this->ensureExpectedType('<<', $expectedType);
                    $this->streamReader->addOffset(1);
                    return PdfDictionary::parse($this->tokenizer, $this->streamReader, $this);
                }

                $this->ensureExpectedType($token, $expectedType);
                return PdfHexString::parse($this->streamReader);

            case '/':
                $this->ensureExpectedType($token, $expectedType);
                return PdfName::parse($this->tokenizer, $this->streamReader);

            case '[':
                $this->ensureExpectedType($token, $expectedType);
                return PdfArray::parse($this->tokenizer, $this);

            default:
                if (\is_numeric($token)) {
                    if (($token2 = $this->tokenizer->getNextToken()) !== false) {
                        if (\is_numeric($token2)) {
                            if (($token3 = $this->tokenizer->getNextToken()) !== false) {
                                switch ($token3) {
                                    case 'obj':
                                        if ($expectedType !== null && $expectedType !== PdfIndirectObject::class) {
                                            throw new Type\PdfTypeException(
                                                'Got unexpected token type.', Type\PdfTypeException::INVALID_DATA_TYPE
                                            );
                                        }

                                        return PdfIndirectObject::parse(
                                            $token,
                                            $token2,
                                            $this,
                                            $this->tokenizer,
                                            $this->streamReader
                                        );
                                    case 'R':
                                        if ($expectedType !== null &&
                                            $expectedType !== PdfIndirectObjectReference::class
                                        ) {
                                            throw new Type\PdfTypeException(
                                                'Got unexpected token type.', Type\PdfTypeException::INVALID_DATA_TYPE
                                            );
                                        }

                                        return PdfIndirectObjectReference::create($token, $token2);
                                }

                                $this->tokenizer->pushStack($token3);
                            }
                        }

                        $this->tokenizer->pushStack($token2);
                    }

                    if ($expectedType !== null && $expectedType !== PdfNumeric::class) {
                        throw new Type\PdfTypeException(
                            'Got unexpected token type.', Type\PdfTypeException::INVALID_DATA_TYPE
                        );
                    }
                    return PdfNumeric::create($token);
                }

                if ($token === 'true' || $token === 'false') {
                    $this->ensureExpectedType($token, $expectedType);
                    return PdfBoolean::create($token === 'true');
                }

                if ($token === 'null') {
                    $this->ensureExpectedType($token, $expectedType);
                    return new PdfNull();
                }

                if ($expectedType !== null && $expectedType !== PdfToken::class) {
                    throw new Type\PdfTypeException(
                        'Got unexpected token type.', Type\PdfTypeException::INVALID_DATA_TYPE
                    );
                }

                $v = new PdfToken();
                $v->value = $token;

                return $v;
        }
    }
1026357
private function _processChargeIssuerResponse($response, $expectedType)
    {
        $transactionId = (isset($response->Header->GatewayTxnId) ? $response->Header->GatewayTxnId : null);
        $item = $response->Transaction->$expectedType;

        if ($item != null) {
            $responseCode = (isset($item->RspCode) ? $item->RspCode : null);
            $responseText = (isset($item->RspText) ? $item->RspText : null);

            if ($responseCode != null) {
                // check if we need to do a reversal
                if ($responseCode == '91') {
                    try {
                        $this->reverse($transactionId, $this->_amount, $this->_currency);
                    } catch (HpsGatewayException $e) {
                        // if the transaction wasn't found; throw the original timeout exception
                        if ($e->details->gatewayResponseCode == 3) {
                            HpsIssuerResponseValidation::checkResponse($transactionId, $responseCode, $responseText);
                        }
                        throw new HpsCreditException(
                            $transactionId,
                            HpsExceptionCodes::ISSUER_TIMEOUT_REVERSAL_ERROR,
                            'Error occurred while reversing a charge due to HPS issuer timeout',
                            $e
                        );
                    } catch (HpsException $e) {
                        throw new HpsCreditException(
                            $transactionId,
                            HpsExceptionCodes::ISSUER_TIMEOUT_REVERSAL_ERROR,
                            'Error occurred while reversing a charge due to HPS issuer timeout',
                            $e
                        );
                    }
                }
                HpsIssuerResponseValidation::checkResponse($transactionId, $responseCode, $responseText);
            }
        }
    }