Handle response from the server

@return mixed
@throws Exception
514239
public function processResponse()
    {
        // Init results
        $results = [];

        foreach ($this->packets_response as $response) {
            $buffer = new Buffer($response);

            // Figure out what packet response this is for
            $response_type = $buffer->read(6);

            // Figure out which packet response this is
            if (!array_key_exists($response_type, $this->responses)) {
                throw new Exception(__METHOD__ . " response type '" . bin2hex($response_type) . "' is not valid");
            }

            // Now we need to call the proper method
            $results = array_merge(
                $results,
                call_user_func_array([$this, $this->responses[$response_type]], [$buffer])
            );

            unset($buffer);
        }

        return $results;
    }
686047
public function prepareResponse()
    {
        try {
            $this->setBaseMiddlewares();
            $this->handleRequest($this->middlewares);
            $this->router->build();
            $this->handleRequest($this->routeMiddlewares);
            $this->response = $this->router->run();
        } catch (Exception $exception) {
            $response = $this->container->call([$this->getExceptionHandler(), 'render'], [$exception]);
            $this->response = $response ?: $this->response;
        }
    }
644081
protected function handleException()
    {
        $this->handleNotJsonException($this->getResponse());

        if (false === $this->getInstapushClient()->isHandleException()) {
            return $this
                ->getInstapushClient()
                ->getTransformer()
                ->transform($this->getResponse(), ApiError::class);
        }

        $content = \json_decode($this->getResponse()->getBody()->__toString(), true);

        $message = true === isset($content['msg']) ? $content['msg'] : 'An unexpected error occurred : '.$content;

        throw new ApiException($message, $this->getRequest(), $this->getResponse());
    }
1045853
public function handler(): Response
    {
        if ($this->redirect) {
            return response(null, 302, ['Location' => $this->redirect]);
        } elseif ($this->request->query->has('error')) {
            return view('error.twig', [
                'error' => $this->request->query->get('error'),
                'message' => $this->request->query->get('message')
            ]);
        } else {
            $this->addAssets();
            return view($this->template, $this->data);
        }
    }
1058375
public function handler(): Response
    {
        $data = $this->validate([
            'email' => [
                new Email()
            ],
            'phone' => []
        ]);
        $member = Member::search($this->getParameter('username'));
        if (!$member) {
            throw new HttpNotFoundException();
        }
        $member->update($data);
        $this->log('info', 'Update member [' . $member->getUsername() . ']');
        return response();
    }
532836
public function handler(): Response
    {
        $chinese = $this->request->get('chinese', '');
        $pinyin = new Pinyin();
        return response([
            'chinese' => $chinese,
            'pinyin' => $pinyin->convert($chinese)
        ]);
    }
155261
public function handle(
        ServerRequestInterface $request,
        ResponseInterface $response = null,
        $catch = self::DEFAULT_ERROR_CATCH
    )
    {
        /** @var ResponseInterface $response */
        // Passes the request to the container
        if (!$this->getContainer()->has(ServerRequestInterface::class)) {
            $this->getContainer()->share(ServerRequestInterface::class, $request);
        }

        //inject request content type
        $contentType = ServerRequestFactory::getHeader('content-type', $this->getRequest()->getHeaders(), '');
        $this->setContentType($contentType);

        if ($response === null) {
            $response = $this->getResponse();
        }

        $applicationEvent = $this->getApplicationEvent();
        $applicationEvent->setRequest($request);
        $applicationEvent->setResponse($response);

        try {
            $response = $this->handleResponse($this->handleRequest($request), $response);
        }catch (\Exception $exception){
            $notFoundException = $exception instanceof NotFoundException;
            $response = $this->handleError($exception, $request, $response, $catch)
                ->withStatus($notFoundException ? 404 : 500);
        }

        // validate response
        $response = $this->validateContract($response, ResponseInterface::class);

        // update content type
        $this->setContentType(ServerRequestFactory::getHeader('content-type', $response->getHeaders(), ''));

        return $response;
    }
251762
public function handler(): Response
    {
        $data = $this->validate([
            'name' => [
                new NotBlank()
            ],
            'slug' => [
                new NotBlank()
            ],
            'icon' => [],
            'color' => []
        ]);
        $role = new Role($data);
        $role->save();
        $this->log('info', 'Create a role [' . $role->getSlug() . ']');
        return response([
            'id' => $role->getId()
        ]);
    }
807854
public function handler(): Response
    {
        $response = [];
        foreach (Mailer::all() as $mailer) {
            $response[] = [
                'id' => $mailer->getId(),
                'default' => $mailer->getDefault(),
                'remark' => $mailer->getRemark(),
                'driver' => $mailer->getDriver(),
                'host' => $mailer->getHost(),
                'port' => $mailer->getPort(),
                'encryption' => $mailer->getEncryption(),
                'username' => $mailer->getUsername(),
                'password' => $mailer->getPassword(),
                'sender' => $mailer->getSender()
            ];
        }
        return response($response);
    }
115676
public function get_response() {
        // Lets log the Exception, Just in case it's important!
        Kohana_Exception::log($this);

        if (Kohana::$environment >= Kohana::DEVELOPMENT) {
        //if (0) {
            // Show the normal Kohana error page.
            return parent::get_response();
        } else {
            return self::_handler($this);
            //var_dump(get_included_files());
            //var_dump(Route::all());
            //var_dump($this->getTrace());
            //exit($this->getTraceAsString());
            $params = array                (
                'action' => $this->getCode(),
                'message' => rawurlencode($this->getMessage())
            );
            // Error sub-request.
            return Request::factory(Route::get('error')->uri($params))
                    ->execute();
        }
    }
274632
public function handler(): Response
    {
        $bulletin = Bulletin::find($this->getParameter('id'));
        if (!$bulletin) {
            throw new HttpNotFoundException();
        }
        if ($bulletin->isDraft()) {
            $bulletin->publish();
            $this->log('info', 'Publish a bulletin [' . $bulletin->getId() . ']');
        } else {
            throw new HttpForbiddenException();
        }
        return response();
    }
214148
public function execute() {

		// Register all handles and monitor that
		// all requests are executed
		$handleExecutionCounter = array();

		foreach( $this->httpRequests as $httpRequest ) {
			$httpRequest->setOption( CURLOPT_RETURNTRANSFER, true );
			$handleExecutionCounter[(int)  $httpRequest() ] = true;
			curl_multi_add_handle( $this->handle, $httpRequest() );
		}

		$response = $this->doMakeMultiRequest( $handleExecutionCounter );

		return $response;
	}
1296390
public function serverResponse()
    {
        try
        {
            $this->generator->serverResponse();
        }
        catch(\Exception $exception)
        {
            // Handle server generating image response exception
            if($this->handleExceptions)
            {
                if(is_string($this->handleExceptions))
                {
                    Debugger::log($exception->getMessage(), $this->handleExceptions);
                }
                else
                {
                    Debugger::log($exception, 'palette');
                }
            }
            else
            {
                throw $exception;
            }

            // Return fallback image on exception if fallback image is configured
            $fallbackImage = $this->generator->getFallbackImage();

            if($fallbackImage)
            {
                $paletteQuery = preg_replace('/.*@(.*)/', $fallbackImage . '@$1', $_GET['imageQuery']);

                $picture  = $this->generator->loadPicture($paletteQuery);
                $savePath = $this->generator->getPath($picture);

                if(!file_exists($savePath))
                {
                    $picture->save($savePath);
                }

                $picture->output();
            }
        }
    }
997014
public function handleRequest()
    {
        $request = $this->prepareRequest();
        $version = $request['version'];
        $queryConfiguration = $request['queryConfiguration'];

        $data = $this->provider->process();
        return $version->createResponse($data, $queryConfiguration, $this->columnConfigurations);
    }
1346575
public function process()
    {
        //formulate the request and response
        $request = $this->getRequest();
        $response = $this->getResponse();
        
        //register shutdown
        register_shutdown_function(function ($server) {
            $server->trigger('server-end');
        }, $this);
        
        //if it's not a child
        if (!($this->parentServer instanceof Index)) {
            //handle errors in case
            $this->handleErrors($request, $response);
        }
        
        //if we are Good, route
        if ($this->processGlobal($request, $response)) {
            //if no routing on this
            if (!$this->processRoutes($request, $response)) {
                $response->set('code', 404);
                
                //throw an exception
                Exception::i()
                    ->setMessage(self::NOT_FOUND)
                    ->setType(self::RESPONSE_ERROR_TYPE)
                    ->trigger();
            }
        }
        
        //do we have a body ?
        $body = $response->get('body');
        
        if ($body === null
        || !is_scalar($body)
        || !strlen((string) $body)) {
            $response->set('code', 404);
            
            //throw an exception
            Exception::i()
                ->setMessage(self::NOT_FOUND)
                ->setType(self::RESPONSE_ERROR_TYPE)
                ->trigger();
        }
        
        return array($request, $response);
    }
465557
private function handleHTTP()
    {
    	try
    	{
			$method = new ReflectionMethod($this->classname, $_REQUEST["svc"]);
    	}
    	catch (Exception $ex)
    	{
    		echo '{ error: "Method does not exists" }';
    		exit;
    	}
		if (!$method->isPublic())
		{
    		echo '{ error: "Method is not public" }';
			exit;
		}

		$params = $method->getParameters();
		$paramValues = array();
		$missingParams = array();
		foreach ($params as $param)
		{
			$paramName = $param->getName();
			$paramValue = ( isset($_REQUEST[$paramName]) ? $_REQUEST[$paramName] : null);
			if (is_null($paramValue) && $param->isDefaultValueAvailable())
			{
				$paramValue = $param->getDefaultValue();
			}
			if (is_null($paramValue))
			{
				$missingParams[] = $paramName;
			}
			else
			{
				$paramValues[$paramName] = $paramValue;
			}
		}
		if (count($missingParams) > 0)
		{
			echo '{ error: "Missing params", parameters: [ "' . implode('","', $missingParams) . '"] }';
		}
		else
		{
			try
			{
				$result = $method->invokeArgs($this, $paramValues);
				if (is_array($result))
				{
					echo json_encode($result);
				}
				elseif (is_object($result))
				{
					echo '{ error: "Return type is not supported" } ';
				}
				else
				{
					echo $result;
				}
			}
			catch (Exception $ex)
			{
				echo '{ error: "' . $ex->getMessage() . '" }';
			}
		}
    }
450774
private function RunRequest()
    {
        $result = curl_exec($this->_curlHandle);
        if ($result === false && curl_errno($this->_curlHandle) != 0) {
            $this->logger->error("cURL error: " . curl_error($this->_curlHandle));
            throw new Exception('cURL error: ' . curl_error($this->_curlHandle));
        }

        $response = new HttpResponse();
        $response->ResponseCode = (int) curl_getinfo($this->_curlHandle, CURLINFO_HTTP_CODE);

        curl_close($this->_curlHandle);

        $explode = explode("\r\n\r\n", $result);

        // multiple query (follow redirect) take only the last request
        $explode = array_slice($explode, sizeof($explode) - 2, 2);

        $response->Headers = explode("\n", implode($explode));
        $response->Body = array_pop($explode);

        return $response;
    }