Process the raw JSON response, given from conduit.
Throw an exception when given JSON is malformed

@param $rawResult

@throws \BuildR\Foundation\Exception\RuntimeException

@return mixed
422549
protected function processRawResponse($rawResult) {
        $result = json_decode($rawResult, TRUE);

        if(json_last_error() !== JSON_ERROR_NONE) {
            throw new RuntimeException('Malformed JSON response! Message: ' . json_last_error_msg());
        }

        return $result;
    }
586055
public function execute( $query, $rawData = false ) {

    if ( strlen( $query ) > self::MAX_GET_SIZE ) {
      // big requests go to POST
      $this->method = 'POST';
    }

    $client = new Client();

    $response = $client->request( $this->method, self::SPARQL_ENDPOINT, [
        'query' => [ 
          "query" => $query, 
          "format" => "json",
          "maxQueryTimeMillis" => $this->timeout * 1000
        ]
    ]);

    $status = $response->getStatusCode();

    if ( $status != '200' ) {
      throw new Exception( 'HTTP Error' );
    }

    $result = $response->getBody();

    $data = json_decode( $result, true );
    
    if ( $data === null || $data === false ) {
      throw new Exception( "HTTP request failed, response:\n" .
        substr( $result, 1024 ) );
    }

    return $this->extractData( $data, $rawData );
  }
90058
public function processResponse()
    {

        // Try to json_decode, make it into an array
        if (($data = json_decode(implode('', $this->packets_response), true)) === null) {
            throw new Exception(__METHOD__ . " Unable to decode JSON data.");
        }

        // Set the result to a new result instance
        $result = new Result();

        // Always dedicated
        $result->add('dedicated', 1);

        // Let's iterate over the response items, there are a lot
        foreach ($data as $key => $value) {
            // Ignore root for now, that is where all of the channel/player info is housed
            if (in_array($key, ['root'])) {
                continue;
            }

            // Add them as is
            $result->add($key, $value);
        }

        // Offload the channel and user parsing
        $this->processChannelsAndUsers($data['root'], $result);

        unset($data);

        // Manually set the number of players
        $result->add('numplayers', count($result->get('players')));

        return $result->fetch();
    }
246037
public function rawResponseToArray($responseRaw, $format)
    {
        $responseDecoded = [];
        if (!empty(trim($responseRaw))) {
            switch ($format) {
                case 'json':
                    $responseDecoded = $this->rawJsonToArray($responseRaw);
                    break;
                case 'xml':
                    $responseDecoded = $this->rawXmlToArray($this->lastCurlResponse);
                    break;
                case 'txt':
                default:
                    $responseDecoded = [$this->lastCurlResponse];
                    break;
            }
        }
        return $responseDecoded;
    }
406970
public function execute(AbstractResult $result)
    {
            $query = http_build_query(
                $this->getParams()
            );

            $url      = $this->apiUrl . $this->getMethod() . '?' . $query;
            $response = $this->downloader->download($url);

            $responseJson = json_decode($response);
            if ( ! $responseJson) {
                throw new RuntimeException('Failed to parse Response. Invalid Json: ' . $response);
            }

            if (isset($responseJson->errno)) {
                throw new ApiException($responseJson->errmsg, $responseJson->errno);
            }
            $result->parseResponse($responseJson);
            $result->setQueryUrl($url);

            return $result;
    }
238517
public static function createFromRaw(string $rawResponse, string $responseClassName = Response::class): ResponseInterface
    {
        $response = new $responseClassName();

        if (!$response instanceof ResponseInterface) {
            throw new \InvalidArgumentException(sprintf('The given response class name "%s" does not implement the "%s" and cannot be created with this method.', $responseClassName, ResponseInterface::class));
        }

        // see https://tools.ietf.org/html/rfc7230#section-3.5
        $lines = explode(chr(10), $rawResponse);
        $statusLine = array_shift($lines);

        if (substr($statusLine, 0, 5) !== 'HTTP/') {
            throw new \InvalidArgumentException('The given raw HTTP message is not a valid response.', 1335175601);
        }
        list($httpAndVersion, $statusCode, $reasonPhrase) = explode(' ', $statusLine, 3);
        $version = explode('/', $httpAndVersion)[1];
        if (strlen($statusCode) !== 3) {
            // See https://tools.ietf.org/html/rfc7230#section-3.1.2
            throw new \InvalidArgumentException('The given raw HTTP message contains an invalid status code.', 1502981352);
        }
        $response = $response->withStatus((integer)$statusCode, trim($reasonPhrase));
        $response = $response->withProtocolVersion($version);

        $parsingHeader = true;
        $contentLines = [];
        $headers = new Headers();
        foreach ($lines as $line) {
            if ($parsingHeader) {
                if (trim($line) === '') {
                    $parsingHeader = false;
                    continue;
                }
                $headerSeparatorIndex = strpos($line, ':');
                if ($headerSeparatorIndex === false) {
                    throw new \InvalidArgumentException('The given raw HTTP message contains an invalid header.', 1502984804);
                }
                $fieldName = trim(substr($line, 0, $headerSeparatorIndex));
                $fieldValue = trim(substr($line, strlen($fieldName) + 1));
                if (strtoupper(substr($fieldName, 0, 10)) === 'SET-COOKIE') {
                    $cookie = Cookie::createFromRawSetCookieHeader($fieldValue);
                    if ($cookie !== null) {
                        $headers->setCookie($cookie);
                    }
                } else {
                    $headers->set($fieldName, $fieldValue, false);
                }
            } else {
                $contentLines[] = $line;
            }
        }
        if ($parsingHeader === true) {
            throw new \InvalidArgumentException('The given raw HTTP message contains no separating empty line between header and body.', 1502984823);
        }
        $content = implode(chr(10), $contentLines);

        $response->setHeaders($headers);
        $response = $response->withBody(ArgumentsHelper::createContentStreamFromString($content));

        return $response;
    }
830026
public function receive($raw)
    {
        if ($this->verify) {
            $this->validateRequest();
        }

        $incomingMessage = $this->createIncomingMessage();
        $incomingMessage->setRaw($raw->get());
        $incomingMessage->setMessage($raw->get('resource_uri'));
        $incomingMessage->setFrom($raw->get('from_number'));
        $incomingMessage->setId($raw->get('message_uuid'));
        $incomingMessage->setTo($raw->get('to_number'));

        return $incomingMessage;
    }
295076
protected function processExportResult(& $result, $format)
    {
        if ($format == 'php') {
            $phpResult = json_decode($result, true); // true => return as array instead of object
                
            $jsonError = json_last_error();
                
            switch ($jsonError) {
                case JSON_ERROR_NONE:
                    $result = $phpResult;
                    break;
                default:
                    $message =  "JSON error (" . $jsonError . ") \"" . json_last_error_msg()
                        ."\" in REDCap API output."
                        ."\nThe first 1,000 characters of output returned from REDCap are:\n"
                        .substr($result, 0, 1000);
                    $code = ErrorHandlerInterface::JSON_ERROR;
                    $this->errorHandler->throwException($message, $code);
                    break; // @codeCoverageIgnore
            }
                
            if (array_key_exists('error', $result)) {
                $this->errorHandler->throwException($result ['error'], ErrorHandlerInterface::REDCAP_API_ERROR);
            } // @codeCoverageIgnore
        } else {
            // If this is a format other than 'php', look for a JSON error, because
            // all formats return errors as JSON
            $matches = array();
            $hasMatch = preg_match(self::JSON_RESULT_ERROR_PATTERN, $result, $matches);
            if ($hasMatch === 1) {
                // note: $matches[0] is the complete string that matched
                //       $matches[1] is just the error message part
                $message = $matches[1];
                $this->errorHandler->throwException($message, ErrorHandlerInterface::REDCAP_API_ERROR);
            } // @codeCoverageIgnore
        }
        
        return $result;
    }
358675
protected function _processStream( $inputstream )
	{
		$response = array();

		try
		{
			if( ( $raw = file_get_contents( $inputstream ) ) === false ) {
				throw new Controller_ExtJS_Exception( 'Unable to read JSON encoded request', -32700 );
			}

			if( ( $request = json_decode( $raw ) ) === null ) {
				throw new Controller_ExtJS_Exception( 'Invalid JSON encoded request', -32700 );
			}

			if( is_array( $request ) )
			{
				foreach( $request as $item )
				{
					if( ( $result = $this->_processJson( $item ) ) !== null ) {
						$response[] = $result;
					}
				}
			}
			else if( is_object( $request ) )
			{
				if( ( $result = $this->_processJson( $request ) ) !== null ) {
					$response = $result;
				}
			}
			else
			{
				throw new Controller_ExtJS_Exception( 'Invalid JSON RPC request', -32600 );
			}
		}
		catch( Exception $e )
		{
			$response = array(
				'error' => array(
					'code' => ( $e->getCode() != 0 ? $e->getCode() : -1 ),
					'message' => $e->getMessage(),
				),
				'id' => null,
			);
		}

		if( !empty( $response ) ) {
			return json_encode( $response );
		}

		return null;
	}
1196188
protected function processRequest()
    {
        $route  = $this[ 'request' ]->getRoute();
        $params = $this[ 'request' ]->getParams();

        $controller = $this[ 'router' ]->createController( $route, $params );

        if ( NULL === $controller )
        {
            throw new RawException( 'Failed to Initialise Controller', 404 );
        }

        $this->controller = $controller;

        /** @var IController $controller */
        $controller->run();
    }
816645
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if ($this->checkRequest($request)) {
            try {
                $rawBody = \base64_decode($request->getBody()->getContents());
                if ($rawBody === '') {
                    $request = $request->withParsedBody([])
                        ->withAttribute('ncryptf-decrypted-body', '')
                        ->withAttribute('ncryptf-version', 2)
                        ->withAttribute('ncryptf-request-public-key', \base64_decode($request->getHeaderLine('x-pubkey')));
                } else {
                    $version = Response::getVersion($rawBody);
                    $key = $this->getEncryptionKey($request);

                    $body = $this->decryptRequest($key, $request, $rawBody, $version);

                    $request = $request->withParsedBody(\json_decode($body, true))
                        ->withAttribute('ncryptf-decrypted-body', $body)
                        ->withAttribute('ncryptf-version', $version)
                        ->withAttribute('ncryptf-request-public-key', $version === 2 ? Response::getPublicKeyFromResponse($rawBody) : \base64_decode($request->getHeaderLine('x-pubkey')));
                }
            } catch (DecryptionFailedException | InvalidArgumentException | InvalidSignatureException | InvalidChecksumException | Exception $e) {
                return $this->createResponse(400);
            }
        }

        // Only attempt to process this request if it is a vnd.25519+json or vnd.ncryptf+json request
        // Otherwise, continue with normal processing
        return $handler->handle($request);
    }
510832
public function createResultResponse($result, JsonRpcRequest $fromRequest = null) : JsonRpcResponse
    {
        return $this->createEmptyResponse($fromRequest)
            ->setResult($result);
    }
586315
protected function process()
    {
        $this->result = $this[self::RESPONSE_PROCESSING] != self::TYPE_RAW
            ? DefaultResponseParser::getInstance()->parse($this)
            : $this->request->getResponse();
    }
705172
public function receive($raw)
    {
        //Due to the way EZTexting handles Keyword Submits vs Replys
        //We must check both values.
        $from = $raw->get('PhoneNumber') ? $raw->get('PhoneNumber') : $raw->get('from');
        $message = $raw->get('Message') ? $raw->get('Message') : $raw->get('message');

        $incomingMessage = $this->createIncomingMessage();
        $incomingMessage->setRaw($raw->get());
        $incomingMessage->setFrom($from);
        $incomingMessage->setMessage($message);
        $incomingMessage->setTo('313131');

        return $incomingMessage;
    }
764403
static public function openResult($res) {
		if (!is_array($res))
			throw new Exception('Invalid datatype. Array expected!');

		if (isset($res['error']))
			throw new Exception('Server error: '.$res['error']);

		if (!isset($res['result']))
			throw new Exception('Server returned no result.');

		return $res['result'];
	}
51803
public function parseData(): self
    {
        if (!is_array($this->raw_data)) {
            throw new RunTimeException('Response must be a scalar value');
        }

        $this->product_id = $this->raw_data['product_id'];
        $this->original_transaction_id = $this->raw_data['original_transaction_id'];
        $this->auto_renew_product_id = $this->raw_data['auto_renew_product_id'];
        $this->auto_renew_status = (bool)$this->raw_data['auto_renew_status'];

        if (array_key_exists('expiration_intent', $this->raw_data)) {
            $this->expiration_intent = (int)$this->raw_data['expiration_intent'];
        }

        if (array_key_exists('is_in_billing_retry_period', $this->raw_data)) {
            $this->is_in_billing_retry_period = (int)$this->raw_data['is_in_billing_retry_period'];
        }

        return $this;
    }
537120
public function raw($query, $return = false, $fetchMode = null, $fetchClass = null)
    {
        if (! $return) {
            return $this->exec($query);
        }

        $fetchMode = Database::normalizeFetchType($fetchMode);

        $statement = $this->query($query);

        if ($fetchMode === Database::FETCH_CLASS) {
            $statement->setFetchMode($fetchMode, $fetchClass);
        } else {
            $statement->setFetchMode($fetchMode);
        }

        return $statement->fetchAll();
    }