Processes a response depending on the current state.

@param mixed $response Response returned from the server.

@return mixed
436722
public function process($response)
    {
        if ($this->checkFlags(self::CONNECTED)) {
            return call_user_func($this->processCallback, $this, $response);
        }

        if ($this->checkFlags(self::STREAM_CONTEXT)) {
            return call_user_func($this->streamCallback, $this, $response);
        }

        // TODO: we should handle invalid states in a different manner.
        throw new RuntimeException("Invalid connection state: $this");
    }
509997
public function next($response): ?callable
    {
        if ($this->isEmpty()) {
            return null;
        }

        if (!is_null($response)) {
            return null;
        }

        return $this->pop();
    }
554752
protected function decodeResponse($response)
	{
		$response = json_decode($response, true);
		if (is_null($response))
		{
			throw new RuntimeException('Closure Compiler service returned invalid JSON: ' . json_last_error_msg());
		}

		if (isset($response['serverErrors'][0]))
		{
			$error = $response['serverErrors'][0];

			throw new RuntimeException('Server error ' . $error['code'] . ': ' . $error['error']);
		}

		if (isset($response['errors'][0]))
		{
			$error = $response['errors'][0];

			throw new RuntimeException('Compilation error: ' . $error['error']);
		}

		return $response['compiledCode'];
	}
1136577
protected function parsePayload($response)
    {
        if ($response instanceof ResponseInterface) {
            return $response;
        }

        // TODO: I don't exactly like how we are handling this condition.
        if ($this->closing) {
            return null;
        }

        switch ($response[0]) {
            case self::SUBSCRIBE:
            case self::UNSUBSCRIBE:
            case self::PSUBSCRIBE:
            case self::PUNSUBSCRIBE:
                if ($response[2] === 0) {
                    $this->closing = true;
                }

                return null;

            case self::MESSAGE:
                return (object) [
                    'kind'    => $response[0],
                    'channel' => $response[1],
                    'payload' => $response[2],
                ];

            case self::PMESSAGE:
                return (object) [
                    'kind'    => $response[0],
                    'pattern' => $response[1],
                    'channel' => $response[2],
                    'payload' => $response[3],
                ];

            case self::PONG:
                return (object) [
                    'kind'    => $response[0],
                    'payload' => $response[1],
                ];

            default:
                throw new RuntimeException(
                    "Received an unknown message type {$response[0]} inside of a pubsub context"
                );
        }
    }
773806
protected function getResponseBody($response)
    {
        //Response must be string
        $body = $response;

        if ($response instanceof ResponseInterface) {
            //Fetch the body
            $body = $response->getBody();
        }

        if ($body instanceof StreamInterface) {
            $body = $body->getContents();
        }

        return (string) $body;
    }
629350
protected function interactsWithResponse(Response $response): Response
    {
        if ($response instanceof Filterable && $this instanceof Filterable) {
            $response->setFilterable($this->getFilterable());
        }

        if ($this->validateResponseAutomatically === true) {
            $response->validate();
        }

        return $response;
    }
945991
final public function response($response)
    {
        /**
         * Global Response.
         */
        $registeredResponse = HighPriorityResponse::getResponse();
        if (!is_null($registeredResponse)) {
            return $registeredResponse;
        }

        $this->processOnce();

        /*
         * if rewriteResponse() called
         */
        if (!is_null($this->response)) {
            return value($this->response);
        }

        return $response;
    }
700649
public function makeSingle(Response $response)
    {
        if (!$response->getSuccess()) {
            return null;
        }

        $result = $this->getResultFromResponse($response);

        return $result[0] ?? null;
    }
211000
protected function handleResponse(Response $response)
    {
        $statusCode = $response->getStatusCode();

        switch ($statusCode) {
            case 401:
                $response = $this->processNotAuthorized();
                break;
        }

        return $response;
    }
63602
protected function respond($response)
    {
        if (!isset($response[0])) {
            $success = !(array_key_exists('type', $response) && $response['type'] == 'error')
                && !(array_key_exists('status', $response) && $response['status'] == 'error');

            return $this->mapResponse($success, $response);
        }

        $responses = [];

        foreach ($response as $responds) {
            $success = !(array_key_exists('type', $response) && $response['type'] == 'error')
                && !(array_key_exists('status', $response) && $response['status'] == 'error');

            $responses[] = $this->mapResponse($success, $responds);
        }

        return $responses;
    }
845289
protected function prepareResponse($response)
    {
        if ($response instanceof HTTPResponse) {
            if (isset($_REQUEST['debug_request'])) {
                $class = static::class;
                Debug::message(
                    "Request handler returned HTTPResponse object to {$class} controller;"
                    . "returning it without modification."
                );
            }
            $this->setResponse($response);
        } else {
            // Could be Controller, or ViewableData_Customised controller wrapper
            if (ClassInfo::hasMethod($response, 'getViewer')) {
                if (isset($_REQUEST['debug_request'])) {
                    $class = static::class;
                    $responseClass = get_class($response);
                    Debug::message(
                        "Request handler {$responseClass} object to {$class} controller;"
                        . "rendering with template returned by {$responseClass}::getViewer()"
                    );
                }
                $response = $response->getViewer($this->getAction())->process($response);
            }

            $this->getResponse()->setBody($response);
        }

        //deal with content if appropriate
        ContentNegotiator::process($this->getResponse());
    }
680650
public function after($response)
	{
		// return the template if no response is present and this isn't a RESTful call
		if ( ! $this->is_restful())
		{
			// do we have a response passed?
			if ($response === null)
			{
				// maybe one in the rest body?
				$response = $this->response->body;
				if ($response === null)
				{
					// fall back to the defined template
					$response = $this->template;
				}
			}

			// deal with returned array's in non-restful calls
			elseif (is_array($response))
			{
				$response = \Format::forge()->to_json($response, true);
			}

			// and make sure we have a valid Response object
			if ( ! $response instanceof Response)
			{
				$response = \Response::forge($response, $this->response_status);
			}
		}

		return parent::after($response);
	}
1012111
private function processHttpOkResponse(ResponseInterface $response)
    {
        $body = $this->getBodyAsArray($response);

        if (isset($body['error'])) {
            $response = $this->processHttpOkResponseWithError($body);
        } else {
            $response = $this->processHttpOkResponseWithoutError($body);
        }

        return $response;
    }
946984
public static function decodeHttpResponse($response) {
    $code = $response->getResponseHttpCode();
    $body = $response->getResponseBody();
    $decoded = null;
    
    if ((intVal($code)) >= 300) {
      $decoded = json_decode($body, true);
      $err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl();
      if ($decoded != null && isset($decoded['error']['message'])  && isset($decoded['error']['code'])) {
        // if we're getting a json encoded error definition, use that instead of the raw response
        // body for improved readability
        $err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
      } else {
        $err .= ": ($code) $body";
      }

      throw new ServiceException($err, $code, null, $decoded['error']['errors']);
    }
    
    // Only attempt to decode the response, if the response code wasn't (204) 'no content'
    if ($code != '204') {
      $decoded = json_decode($body, true);
      if ($decoded === null || $decoded === "") {
        throw new ServiceException("Invalid json in service response: $body");
      }
    }
    return $decoded;
  }
983726
private function parseResponse($response) {
        $response = trim($response);
        $this->responseStatus = (int) substr($response, 0, 3);
        $this->response = substr($response, 4);
    }
1007273
public static function respond(Response $response)
    {
        $next = function () use ($response) {
            return $response;
        };

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

        exit;
    }
341515
private function unserializeResponse($response)
    {
        $result = unserialize($response);
        if ($response !== 'b:0;' && $result === false) {
            throw new \Exception(substr($response, 0, 5000));
        }

        return $result;
    }