Фабрика для создания соответствующего исключения на основе результатов от Api.

@param SteeinResponse $response Ответ, вызвавший исключение.

@return ResponseException
428928
public static function create(SteeinResponse $response)
    {
        $data = $response->getDecodedBody();

        if (!isset($data['error']['code']) && isset($data['code'])) {
            $data = ['error' => $data];
        }

        $code = isset($data['error']['code']) ? $data['error']['code'] : null;
        $message = isset($data['error']['message']) ? $data['error']['message'] : 'Неизвестная ошибка из Api.';

        if (isset($data['error']['error_subcode']))
        {
            switch ($data['error']['error_subcode'])
            {
                // Другие проблемы с аутентификацией
                case 458:
                case 459:
                case 460:
                case 463:
                case 464:
                case 467:
                    return new static($response, new AuthenticationException($message, $code));
            }
        }

        switch ($code) {
            // Статус входа или токен устарел, отозван или недействителен
            case 100:
            case 102:
            case 190:
                return new static($response, new AuthenticationException($message, $code));

            // Проблема сервера
            case 1:
            case 2:
                return new static($response, new ServerException($message, $code));

            // Дросселирование API
            case 4:
            case 17:
            case 341:
                return new static($response, new ThrottleException($message, $code));

            // Повторяющаяся запись
            case 506:
                return new static($response, new ClientException($message, $code));
        }

        // Отсутствующие разрешения
        if ($code == 10 || ($code >= 200 && $code <= 299)) {
            return new static($response, new AuthorizationException($message, $code));
        }

        // OAuth ошибка аутентификации
        if (isset($data['error']['type']) && $data['error']['type'] === 'OAuthException') {
            return new static($response, new AuthenticationException($message, $code));
        }

        // Все остальные
        return new static($response, new DefaultException($message, $code));
    }
897305
protected function handleTokenResponse(ResponseInterface $response)
    {
        $statusCode = $response->getStatusCode();
        if (500 <= $statusCode) {
            $e = new ServiceUnavailableException();
            $e->setResponse($response);
            throw $e;
        }

        $contentTypes = $response->getHeader('content-type');
        if (empty($contentTypes) || (0 !== strpos($contentTypes[0], 'application/json') && 0 !== strpos($contentTypes[0], 'text/javascript'))) {
            $e = new UnknownContentTypeException();
            $e->setResponse($response);
            if (!empty($contentTypes)) {
                $e->setContentType($contentTypes[0]);
            }
            throw $e;
        }

        $data = json_decode($response->getBody()->getContents(), true);
        if (200 !== $statusCode) {
            $e = new RequestTokenException();
            $e->setResponse($response);

            if (isset($data['error'])) {
                $e->setError(is_array($data['error']) ? json_encode($data['error']) : $data['error']);
            }

            if (isset($data['error_description'])) {
                $e->setDescription($data['error_description']);
            }

            if (isset($data['error_uri'])) {
                $e->setUri($data['error_uri']);
            }

            throw $e;
        }

        if (isset($data['access_token'])) {
            $this->setAccessToken($data['access_token']);
        }

        return $data;
    }
255960
public function execute($response) {
        global $CFG, $DB;

        $params = $this->parse_template();
        $contextid = $params['context_id'];
        $itemid = $params['item_id'];

        $isget = $response->get_request_method() === 'GET';
        if ($isget) {
            $contenttype = $response->get_accept();
        } else {
            $contenttype = $response->get_content_type();
        }
        // We will receive typeid when working with LTI 1.x, if not the we are in LTI 2.
        $typeid = optional_param('type_id', null, PARAM_ALPHANUM);
        if (is_null($typeid)) {
            if (!$this->check_tool_proxy(null, $response->get_request_data())) {
                $response->set_code(403);
                $response->set_reason("Invalid tool proxy specified.");
                return;
            }
        } else {
            if (!$this->check_type($typeid, $contextid, 'Result.collection:get', $response->get_request_data())) {
                $response->set_code(403);
                $response->set_reason("This resource does not support GET requests.");
                return;
            }
        }
        if (empty($contextid) || (!empty($contenttype) && !in_array($contenttype, $this->formats))) {
            $response->set_code(400);
            $response->set_reason("Invalid request made.");
            return;
        }
        if (!$DB->record_exists('course', array('id' => $contextid))) {
            $response->set_code(404);
            $response->set_reason("Not Found: Course $contextid doesn't exist.");
            return;
        }
        if (!$DB->record_exists('grade_items', array('id' => $itemid))) {
            $response->set_code(404);
            $response->set_reason("Not Found: Grade item $itemid doesn't exist.");
            return;
        }
        $item = $this->get_service()->get_lineitem($contextid, $itemid, $typeid);
        if ($item === false) {
            $response->set_code(403);
            $response->set_reason("Line item does not exist.");
            return;
        }
        $gbs = gradebookservices::find_ltiservice_gradebookservice_for_lineitem($itemid);
        $ltilinkid = null;
        if (isset($item->iteminstance)) {
            $ltilinkid = $item->iteminstance;
        } else if ($gbs && isset($gbs->ltilinkid)) {
            $ltilinkid = $gbs->ltilinkid;
        }
        if ($ltilinkid != null) {
            if (is_null($typeid)) {
                if (isset($item->iteminstance) && (!gradebookservices::check_lti_id($ltilinkid, $item->courseid,
                        $this->get_service()->get_tool_proxy()->id))) {
                    $response->set_code(403);
                    $response->set_reason("Invalid LTI id supplied.");
                    return;
                }
            } else {
                if (isset($item->iteminstance) && (!gradebookservices::check_lti_1x_id($ltilinkid, $item->courseid,
                        $typeid))) {
                    $response->set_code(403);
                    $response->set_reason("Invalid LTI id supplied.");
                    return;
                }
            }
        }
        require_once($CFG->libdir.'/gradelib.php');
        switch ($response->get_request_method()) {
            case 'GET':
                $useridfilter = optional_param('user_id', 0, PARAM_INT);
                $limitnum = optional_param('limit', 0, PARAM_INT);
                $limitfrom = optional_param('from', 0, PARAM_INT);
                $typeid = optional_param('type_id', null, PARAM_TEXT);
                $json = $this->get_json_for_get_request($item->id, $limitfrom, $limitnum,
                        $useridfilter, $typeid, $response);
                $response->set_content_type($this->formats[0]);
                $response->set_body($json);
                break;
            default:  // Should not be possible.
                $response->set_code(405);
                $response->set_reason("Invalid request method specified.");
                return;
        }
        $response->set_body($json);
    }
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);
        }

    }
832494
protected function checkResponse(Response $response)
    {
        $statusCode = $response->getStatusCode();

        if ($statusCode >= 300) {
            throw new RestException($statusCode, $response->getContent());
        }

        return $response;
    }
958849
public function getResultFromResponse(Response $response)
    {
        $buckets = $response->getData()['aggregations']['variant']['buckets'];

        foreach ($buckets as $bucket) {

            $source = $bucket['value']['hits']['hits'][0]['_source'];

            $data = json_decode($source['scope'], true);
            $element = $data['data'][0];
            $included = $data['included'];

            $included = $this->getIncludedArray($included);
            $mapperClass = $this->getMapperClass($element['type']);

            if (is_null($mapperClass)) {
                throw new EntityNotFoundException("Entity mapper class for {$element['type']} was not found");
            }

            $element['attributes'] = array_merge($element['attributes'], $source);
            $result[] = $this->createObject($mapperClass, $element, $included);
        }

        return $result ?? [];
    }
1097946
protected function toHttpResponse( $response, Exception $e )
	{
		$response = new Response( $response->getContent(), $response->getStatusCode(), $response->headers->all() );

		return $response->withException( $e );
	}
985927
private function throwExceptionOnHttpErrors(Response $response)
    {
        $httpCode = $response->getHttpCode();

        if ($httpCode >= 400)
        {
            // Get the description of the http error code
            $httpMessage = $response->getHttpMessage($httpCode);

            throw new HttpException($response, $httpMessage, $httpCode);
        }
    }
1019653
protected function errorCheckResponse(ResponseInterface $response)
    {
        $body = $response->getBody();

        if ($response->getStatusCode() >= 400) {
            throw new HttpException($response);
        }

        $responseObject = @json_decode($this->streamToString($body));
        if (!isset($responseObject)) {
            throw new Exception('JSON returned is not valid', $response);
        }

        if (isset($responseObject->error)) {
            throw new Exception($responseObject->error, $response);
        }
    }
1007273
public static function respond(Response $response)
    {
        $next = function () use ($response) {
            return $response;
        };

        (new static())->handle(Request::capture(), $next)->send();

        exit;
    }
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;
    }
968477
public function serveResponse(ResponseInterface $response)
    {
        // add increment
        $this->servedResponseCount++;
        $allowServeEmpty = $this->getConfiguration('serveEmptyResponse') === true;
        $setContentLength = $this->getConfiguration('setContentLength') === true;
        // Send response
        if (!headers_sent()) {
            // Headers
            foreach ($response->getHeaders() as $name => $values) {
                if (!$setContentLength && strtolower($name) === 'content-length') {
                    continue;
                }

                foreach ($values as $value) {
                    header(sprintf('%s: %s', $name, $value), false);
                }
            }

            // Re Set Status Header
            header(sprintf(
                'HTTP/%s %s %s',
                $response->getProtocolVersion(),
                $response->getStatusCode(),
                $response->getReasonPhrase()
            ), true, $response->getStatusCode());
        }

        // Serve Response
        if ($allowServeEmpty || ! $this->isEmptyResponseCode($response->getStatusCode())) {
            $body = $response->getBody();
            if ($body->isSeekable()) {
                $body->rewind();
            }

            $chunkSize      = $this->getNormalizeResponseChunkSize();
            $contentLength  = $setContentLength
                ? $response->getHeaderLine('Content-Length')
                : null;

            if (!$contentLength) {
                $contentLength = $body->getSize();
                // set content length
                if ($setContentLength && !headers_sent()) {
                    header(sprintf('Content-Length: %d', $contentLength));
                }
            }

            // if use buffer create buffer
            $this->addCreateBuffer();
            if ($contentLength) {
                $amountToRead = $contentLength;
                while ($amountToRead > 0 && !$body->eof()) {
                    $data = $body->read(min($chunkSize, $amountToRead));
                    echo $data;
                    $amountToRead -= strlen($data);
                    if (connection_status() != CONNECTION_NORMAL) {
                        break;
                    }
                }
            } else {
                while (!$body->eof()) {
                    echo $body->read($chunkSize);
                    if (connection_status() != CONNECTION_NORMAL) {
                        break;
                    }
                }
            }
        }
    }
1153798
public function validateResponse(Response $response)
	{
		$xml = simplexml_load_string($response->body);

		if (isset($xml->warnings))
		{
			throw new \DomainException($xml->warnings->info);
		}

		if (isset($xml->error))
		{
			throw new \DomainException($xml->error['info']);
		}

		return $xml;
	}
618209
public static function parseResponse(Response $response)
    {
        $jsonData = \GuzzleHttp\json_decode($response->getBody(), true);
        if ($jsonData && 0 == $jsonData['retcode']) {
            $markNames = (new Collection($jsonData['result']['gmarklist']))->combine('uin', 'markname')
                ->toArray();
            $groups = [];
            foreach ($jsonData['result']['gnamelist'] as $groupData) {
                $groupId = $groupData['gid'];
                $groupData['id'] = $groupData['gid'];
                $groupData['markName'] = isset($markNames[$groupId]) ? $markNames[$groupId] : '';
                $group = EntityFactory::createEntity(Group::class, $groupData);
                $groups[] = $group;
            }

            return new EntityCollection($groups);
        }
        throw new ResponseException($jsonData['retcode'], $response);
    }
103354
public function handleResponse($response)
    {
        switch (true) {
            // Render default template and use $response as template variables
            case is_array($response) :
                $content = $this->view->render($this->getDefaultTemplate(), $response);

                return $this->response->setContent($content);

            // Response directly
            case is_scalar($response) || is_null($response) :
                return $this->response->setContent($response);

            // Response if not sent
            case $response instanceof Response :
                return $response;

            default :
                throw new \InvalidArgumentException(sprintf(
                    'Expected argument of type array, printable variable or \Wei\Response, "%s" given',
                    is_object($response) ? get_class($response) : gettype($response)
                ));
        }
    }
1158296
protected function getResponseTransfer(array $response): ComputopApiReverseResponseTransfer
    {
        $computopApiResponseTransfer = new ComputopApiReverseResponseTransfer();
        $computopApiResponseTransfer->setHeader(
            $this->computopApiService->extractResponseHeader($response, $this->config->getReverseMethodName())
        );
        //optional fields
        $computopApiResponseTransfer->setAId($this->computopApiService->getResponseValue($response, ComputopApiConfig::A_ID));
        $computopApiResponseTransfer->setTransactionId($this->computopApiService->getResponseValue($response, ComputopApiConfig::TRANSACTION_ID));
        $computopApiResponseTransfer->setCodeExt($this->computopApiService->getResponseValue($response, ComputopApiConfig::CODE_EXT));
        $computopApiResponseTransfer->setErrorText($this->computopApiService->getResponseValue($response, ComputopApiConfig::ERROR_TEXT));
        $computopApiResponseTransfer->setRefNr($this->computopApiService->getResponseValue($response, ComputopApiConfig::REF_NR));

        return $computopApiResponseTransfer;
    }
731888
protected function prepareErrorResponse($exception, Http\Response $response)
    {
        $pathPosition = strpos($exception->getFile(), 'Packages/');
        $filePathAndName = ($pathPosition !== false) ? substr($exception->getFile(), $pathPosition) : $exception->getFile();
        $exceptionCodeNumber = ($exception->getCode() > 0) ? '#' . $exception->getCode() . ': ' : '';
        $content = PHP_EOL . 'Uncaught Exception in Flow ' . $exceptionCodeNumber . $exception->getMessage() . PHP_EOL;
        $content .= 'thrown in file ' . $filePathAndName . PHP_EOL;
        $content .= 'in line ' . $exception->getLine() . PHP_EOL . PHP_EOL;
        $content .= Debugger::getBacktraceCode($exception->getTrace(), false, true) . PHP_EOL;

        if ($exception instanceof Exception) {
            $statusCode = $exception->getStatusCode();
        } else {
            $statusCode = 500;
        }
        $response->setStatus($statusCode);
        $response->setContent($content);
        $response->setHeader('X-Flow-ExceptionCode', $exception->getCode());
        $response->setHeader('X-Flow-ExceptionMessage', $exception->getMessage());
    }