Encode and return status response.

@param  StatusResponse    $action_result
@param  ResponseInterface $response
@return ResponseInterface
493276
protected function encodeStatus(StatusResponse $action_result, ResponseInterface $response)
    {
        $response = $response->withStatus($action_result->getHttpCode(), $action_result->getMessage());

        if ($action_result->getHttpCode() >= 400) {
            $response = $response->write(json_encode(['message' => $action_result->getMessage()]));
        }

        return $response;
    }
1343012
protected function ensureResponse($output)
    {
        if ($output instanceof Response)
        {
            return $output;
        }
        elseif (is_string($output))
        {
            return Response::create($output, 200);
        }
        else
        {
            $message = "Action response cannot be served.";
            throw new ApplicationException($message);
        }
    }
781401
private function encodeUserSessionResponse(UserSessionResponseInterface $action_result, ServerRequestInterface $request, ResponseInterface $response)
    {
        if ($action_result->getAuthenticatedWith() instanceof  SessionInterface) {
            $response = $this->getCookiesProvider()->set($request, $response, $this->getUserSessionIdCookieName(), $action_result->getAuthenticatedWith()->getSessionId(), [
                'ttl' => 1209600,
                'http_only' => true,
            ])[1];
        }

        return $this->encodeArray($action_result->toArray(), $response);
    }
678495
public function response($data, $format, $is_success=true, $status_code = 200)
    {
        $this->httpCode($status_code);
        if ($is_success) {
            $data['status'] = 1;
        } else {
            $data['status'] = 0;
        }
        switch ($format) {
            case self::RESPONSE_TYPE_JSON:
                $response_content = JsonHelper::encode($data);
                break;
            case self::RESPONSE_TYPE_XML:
                header('Content-type:application/xml');
                $response_content = XMLHelper::encode($data);
                break;
            default:
                $response_content = '';
        }
        if (!$is_success) {
            Lb::app()->stop($response_content);
        } else {
            echo $response_content;
        }
    }
329255
public function mapResponse($response, $statusCode)
    {
        // IPN response
        if (in_array(Arr::get($response, 'body'), ['VERIFIED', 'INVALID'])) {
            $success = $response['body'] === 'VERIFIED';

            return (new Response())->setRaw($response)->map([
                'isRedirect'      => false,
                'success'         => $success,
                'reference'       => $success ? Arr::get($response, 'invoice') : false,
                'message'         => $response['body'],
                'test'            => $this->config['test'],
                'authorization'   => $success ? Arr::get($response, 'txn_id') : '',
                'status'          => $success ?
                    $this->getPaymentStatus(Arr::get($response, 'payment_status'))
                    : new Status('failed'),
                'errorCode'       => null,
                'type'            => $success ? Arr::get($response, 'txn_type') : null,
            ]);
        }

        $isRedirect = isset($response['is_redirect']) ? $response['is_redirect'] : false;
        if ($isRedirect) {
            unset($response['is_redirect']);
        }

        // Payment request / execute response
        $type = $this->getType($response);
        $state = $this->getSuccessAndStatus($response, $statusCode, $type, $isRedirect);
        $success = $state['success'];
        $status = $state['status'];
        $reference = $state['reference'];
        $authorization = $state['authorization'];
        $message = $success ? 'Transaction approved' : Arr::get($response, 'message', '');

        return (new Response())->setRaw($response)->map([
            'isRedirect'    => $isRedirect,
            'success'       => $success,
            'reference'     => $reference,
            'message'       => $message,
            'test'          => $this->config['test'],
            'authorization' => $authorization,
            'status'        => $status,
            'errorCode'     => $success ? null : $this->getErrorCode(Arr::get($response, 'name')),
            'type'          => $type,
        ]);
    }
1117896
public function dispatch(ResponseInterface $response, int $status, $result)
    {
        // Build output array
        $contents = [
            'status' => $status,
            'result' => $result,
        ];

        // Convert output to JSON
        $contents = json_encode($contents, JSON_PRETTY_PRINT);

        // Write Response to Body
        $response->getBody()->write($contents);

        // PSR-7 response
        return $response->withStatus($status); 
    }
402920
public function process(\Controller $controller, $result = null)
    {
        if ($controller->getRequest()->isAjax()) {
            $response = $controller->getResponse();
            $response->setStatusCode(200);

            if (is_array($result)) {
                $response->addHeader('Content-Type', 'application/json');
                $response->setBody(json_encode($result));
            }

            return $response;
        } else {
            $controller->redirectBack();
        }

        return null;
    }
431361
private function returnResponse($result): Response
    {
        if ($result instanceof Response) {
            return $result;
        }

        if (is_array($result)) {
            $result = json_encode($result);
        }

        return new Response(200, [], $result);
    }
847311
public function addActionResult($action, $result)
    {
        if (is_null($action)) {
            throw new \RuntimeException(
                'Attempt to provide a result without providing an action',
                1294080509
            );
        }

        $this->results[$action] = $result;
    }
56019
private function postProcessing(JsonResponse $response) {
		$apiUrl = $this->getServiceContainer()->getPreferenceLoader()->getSystemPreferences()->getApiUrl();
		$response->setContent(str_replace('%apiurl%', $apiUrl, $response->getContent()));
		return $response;
	}
884417
private function process(Action $action, EnvironmentInterface $environment)
    {
        $actionMethod = \sprintf(
            'handle%sAllAction',
            \ucfirst($this->getSubmitAction($environment, $this->regardSelectMode($environment)))
        );

        if (false !== ($response = $this->{$actionMethod}($environment, $action))) {
            return $response;
        }

        return null;
    }
281370
public function mapResponse($success, $response)
    {
        return (new Response())->setRaw($response)->map([
            'isRedirect'    => false,
            'success'       => true,
            'reference'     => null,
            'message'       => null,
            'test'          => false,
            'authorization' => null,
            'status'        => $response['status'],
            'errorCode'     => false,
            'type'          => $response['type'],
        ]);
    }
1181872
protected function encodeException($exception, ResponseInterface $response, $status = 500)
    {
        $error = ['message' => $exception->getMessage(), 'type' => get_class($exception)];

        if ($this->getDisplayErrorDetails()) {
            $error['exception'] = [];

            do {
                $error['exception'][] = [
                    'type' => get_class($exception),
                    'code' => $exception->getCode(),
                    'message' => $exception->getMessage(),
                    'file' => $exception->getFile(),
                    'line' => $exception->getLine(),
                    'trace' => explode("\n", $exception->getTraceAsString()),
                ];
            } while ($exception = $exception->getPrevious());
        }

        return $response->write(json_encode($error))->withStatus($status);
    }
1335458
private function resultToResponse($result) : Response
  {
    switch (true) {
      // Response object
      case $result instanceof Response:
        return $result;
      // String -> transform to response
      case is_string($result) || is_numeric($result):
        return new Response($result);
      // Uri -> transform to redirect response
      case $result instanceof Uri:
        return new RedirectResponse($uri);
      // Array -> transform to json response
      case is_array($result) || is_object($result):
        return new JsonResponse($result);
      default:
        throw new \InvalidArgumentException('Invalid route handler return value');
    }
  }
597917
public function mapResponse($success, $response)
    {
        $type = Arr::get($response, 'operation_type');

        list($reference, $authorization) = $success
            ? [Arr::get($response, 'id'), Arr::get($response, 'authorization_code')]
            : [Arr::get($response, 'id'), null];

        $message = $this->getClientMessage($response);

        return (new Response())->setRaw($response)->map([
            'isRedirect'    => false,
            'success'       => $success,
            'reference'     => $reference,
            'message'       => $message,
            'test'          => array_key_exists('live_mode', $response) ? !$response['live_mode'] : false,
            'authorization' => $authorization,
            'status'        => $this->getStatus($response),
            'errorCode'     => $success ? null : $this->getErrorCode($response),
            'type'          => $type,
        ]);
    }
641393
public function renderOutput($response = array(), $status=NULL, $message=NULL)
	{
		http_response_code( $status != NULL ? $status : $this->status );
		header('Content-Type: application/json');
		header("Access-Control-Allow-Origin: *");
		header("Access-Control-Allow-Headers: x-auth-token, x-auth-email");
		header('Access-Control-Allow-Methods: PUT, PATCH, DELETE, POST, GET, OPTIONS');

		// Back-convert the string to a boolean
		if ($response === 'false')
			$response = false;

		echo CJSON::encode(array(
               'status' => $status != NULL ? $status : $this->status,
               'message' => $message != NULL ? $message : ($this->message == NULL ? Yii::t('Api.main', 'Your request was successfully fulfilled') : $this->message),
               'response' => $response
           	));
		Yii::app()->end();
	}
282754
protected function processAction($action, FormInterface $form = null, $statusCode = Response::HTTP_NO_CONTENT)
    {
        $statusCode = $this->getParameterResolver()->resolveStatusCode($statusCode);

        $this->getRestEventDispatcher()->dispatch(
            RestEvents::ACTION,
            $event = new ActionEvent($this->resource, $action, $form, $statusCode)
        );

        $view = $event->getView();
        $statusCode = $view->getStatusCode();

        return $statusCode >= 300 && $statusCode < 400
            ? $this->handleView($view)
            : $this->processView($action, $view);
    }