Map ComproPago response to status object.

@param array $response

@return \Shoperti\PayMe\Status|null
338195
protected function getStatus($response)
    {
        if (isset($response['refunded']) && $response['refunded'] == true) {
            return new Status('refunded');
        }

        if (!isset($response['status']) && !isset($response['type'])) {
            return;
        }

        $status = isset($response['status']) ? $response['status'] : $response['type'];

        switch ($status) {
            case 'pending':
            case 'charge.pending':
                return new Status('pending');
            case 'success':
            case 'charge.success':
                return new Status('paid');
            case 'declined':
            case 'charge.declined':
                return new Status('failed');
            case 'deleted':
            case 'charge.deleted':
                return new Status('canceled');
            case 'expired':
            case 'charge.expired':
                return new Status('voided');
                break;
        }
    }
183668
protected function getPaymentStatus($response)
    {
        $lastPayment = Arr::last($response['payments']);

        // approved, in_process, pending, rejected, cancelled
        // on testing at least, payments may be empty
        return $lastPayment ? Arr::get($lastPayment, 'status', 'other') : 'no_payment';
    }
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"
                );
        }
    }
514176
protected function unserializeResponse($response = null){
        switch($this->getEndpoint()){
            case "json":
                return json_decode($response,true);
                break;
            case "xml":
                return (array) json_decode(json_encode(simplexml_load_string($response, null, LIBXML_NOCDATA)),true);
                break;
            default:
                throw new \ErrorException('Invalid response type');
                break;
        }
    }
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;
  }
823456
public static function toResponse($request, $response)
    {
        if ($response instanceof Responsable) {
            $response = $response->toResponse($request);
        }

        if ($response instanceof PsrResponseInterface) {
            $response = (new HttpFoundationFactory)->createResponse($response);
        } elseif ($response instanceof Model && $response->wasRecentlyCreated) {
            $response = new JsonResponse($response, 201);
        } elseif (! $response instanceof SymfonyResponse &&
                   ($response instanceof Arrayable ||
                    $response instanceof Jsonable ||
                    $response instanceof ArrayObject ||
                    $response instanceof JsonSerializable ||
                    is_array($response))) {
            $response = new JsonResponse($response);
        } elseif (! $response instanceof SymfonyResponse) {
            $response = new Response($response);
        }

        if ($response->getStatusCode() === Response::HTTP_NOT_MODIFIED) {
            $response->setNotModified();
        }

        return $response->prepare($request);
    }
1254853
private function _createRefund(array $response)
    {
        $model = new Refund();
        $model->setId($response['id']);
        $model->setAmount($response['amount']);
        $model->setStatus($response['status']);
        $model->setDescription($response['description']);
        $model->setLivemode($response['livemode']);
        $model->setCreatedAt($response['created_at']);
        $model->setUpdatedAt($response['updated_at']);
        $model->setResponseCode($response['response_code']);
        //Refund doesn't have the array index 'transaction' when using getOne
        $model->setTransaction(isset($response['transaction']) ? $this->_convertResponseToModel($response['transaction'], 'transaction') : null);
        $model->setAppId($response['app_id']);
        return $model;
    }
549955
protected function responseWithHeaders($response)
    {
        foreach ($this->getHeaders() as $key => $value) {
            $response->headers->set($key, $value);
        }

        return $response;
    }
1322969
protected function _httpAuthenticate(Varien_Object $response)
    {
        $result = array(
            'authentication' => false,
            'message' => ''
        );

        $this->fixCgiHttpAuthentication(); //add cgi support
        $internalMerchantAccount = $this->_getConfigData('merchantAccount');
        $username = $this->_getConfigData('notification_username');
        $password = Mage::helper('core')->decrypt($this->_getConfigData('notification_password'));
        $submitedMerchantAccount = $response->getData('merchantAccountCode');

        if (empty($submitedMerchantAccount) && empty($internalMerchantAccount)) {
            if (strtolower(
                substr(
                    $response->getData('pspReference'), 0,
                    17
                )
            ) == "testnotification_" || strtolower(
                substr(
                    $response->getData('pspReference'), 0,
                    5
                )
            ) == "test_") {
                Mage::log(
                    'Notification test failed: merchantAccountCode is empty in magento settings', Zend_Log::DEBUG,
                    "adyen_notification.log", true
                );
                $result['message'] = 'merchantAccountCode is empty in magento settings';
            }

            return $result;
        }

        // validate username and password
        if ((!isset($_SERVER['PHP_AUTH_USER']) && !isset($_SERVER['PHP_AUTH_PW']))) {
            if (strtolower(
                substr(
                    $response->getData('pspReference'), 0,
                    17
                )
            ) == "testnotification_" || strtolower(
                substr(
                    $response->getData('pspReference'), 0,
                    5
                )
            ) == "test_") {
                Mage::log(
                    'Authentication failed: PHP_AUTH_USER and PHP_AUTH_PW are empty. See Adyen Magento manual CGI mode',
                    Zend_Log::DEBUG, "adyen_notification.log", true
                );
                $result['message'] = 'Authentication failed: PHP_AUTH_USER and PHP_AUTH_PW are empty. See Adyen Magento manual CGI mode';
            }

            return $result;
        }

        $accountCmp = !$this->_getConfigData('multiple_merchants')
            ? strcmp($submitedMerchantAccount, $internalMerchantAccount)
            : 0;
        $usernameCmp = strcmp($_SERVER['PHP_AUTH_USER'], $username);
        $passwordCmp = strcmp($_SERVER['PHP_AUTH_PW'], $password);
        if ($accountCmp === 0 && $usernameCmp === 0 && $passwordCmp === 0) {
            $result['authentication'] = true;
            return $result;
        }

        // If notification is test check if fields are correct if not return error
        if (strtolower(
            substr(
                $response->getData('pspReference'), 0,
                17
            )
        ) == "testnotification_" || strtolower(
            substr(
                $response->getData('pspReference'), 0,
                5
            )
        ) == "test_") {
            if ($accountCmp != 0) {
                $result['message'] = "MerchantAccount in notification is not the same as in Magento settings and Allow multiple merchants option is not enabled";
            } elseif ($usernameCmp != 0 || $passwordCmp != 0) {
                $result['message'] = "username (PHP_AUTH_USER) and/or password (PHP_AUTH_PW) are not the same as Magento settings";
            }

            Mage::log($result['message'], Zend_Log::DEBUG, "adyen_notification.log", true);
        }

        return $result;
    }
543883
public function mapResponse($success, $response)
    {
        $rawResponse = $response;

        $object = Arr::get($response, 'object');

        if ($object !== 'error' && array_key_exists('type', $response) && isset($response['data']['object'])) {
            $response = $response['data']['object'];
        }

        $type = $this->getType($rawResponse);
        list($reference, $authorization) = $success ? $this->getReferences($response, $type) : [null, null];

        $message = '';

        if ($success) {
            $message = 'Transaction approved';
        } elseif ($object === 'error') {
            foreach (Arr::get($response, 'details') as $detail) {
                $message .= ' '.Arr::get($detail, 'message', '');
            }
            $message = ltrim($message);
        } else {
            $message = Arr::get($response, 'message_to_purchaser') ?: Arr::get($response, 'message', '');
        }

        $isTest = $object === 'error' && isset($response['data'])
            ? !(Arr::get($response['data'], 'livemode', true))
            : !(Arr::get($response, 'livemode', true));

        if ($type === 'refund') {
            $rawResponse['amount_refunded'] = $this->getRefundAmount($rawResponse);
        }

        return (new Response())->setRaw($rawResponse)->map([
            'isRedirect'    => false,
            'success'       => $success,
            'reference'     => $reference,
            'message'       => $message,
            'test'          => $isTest,
            'authorization' => $authorization,
            'status'        => $success ? $this->getStatus(Arr::get($response, 'payment_status', 'paid')) : new Status('failed'),
            'errorCode'     => $success ? null : $this->getErrorCode($response),
            'type'          => $type,
        ]);
    }
737208
private function _createPreauthorization($response)
    {
        $model = new Preauthorization();
        $model->setId($response['id']);
        $model->setAmount($response['amount']);
        $model->setCurrency($response['currency']);
        $model->setStatus($response['status']);
        $model->setLivemode($response['livemode']);
        $model->setCreatedAt($response['created_at']);
        $model->setUpdatedAt($response['updated_at']);
        $model->setPayment($this->_convertResponseToModel($response['payment'], "payment"));
        $model->setClient($this->_convertResponseToModel($response['client'], "client"));
        $model->setTransaction(isset($response['transaction']) ? $this->_convertResponseToModel($response['transaction'], 'transaction') : null);
        $model->setAppId($response['app_id']);
        $model->setDescription($response['description']);
        return $model;
    }
1208196
private function processResponse($response) {
        list($status, $headers, $body) = $response;
        // if empty response just return boolean
        if ($status == 204) {
            return true;
        }
        
        $decoded = json_decode($body, true);
        if ($decoded === null) {
            throw new RestException('Could not decode response body as JSON.', $status);
        }
        if (200 <= $status && $status < 300) {
            return $decoded;
        }

        throw new RestException(
            $decoded['message'],
            $decoded['code'],
            (isset($decoded['errors']) ? $decoded['errors'] : null)
        );
    }
1246170
protected function evaluateResponse(array $response) {
        if (array_key_exists('error', $response) &&
            $response['error'] !== null) {
            // Validate error object:
            if (!is_array($response['error'])) {
                throw new RuntimeException('Invalid error object');
            }

            if (!array_key_exists('code', $response['error']) ||
                !is_int($response['error']['code']) ||
                $response['error']['code'] >= 0) {
                throw new RuntimeException('Invalid error code');
            }

            if (!array_key_exists('message', $response['error']) ||
                !is_string($response['error']['message']) ||
                strlen($response['error']['message']) === 0) {
                throw new RuntimeException('Invalid error message');
            }

            $details = [];

            if (array_key_exists('data', $response['error']) &&
                is_array($response['error']['data'])) {
                foreach ($response['error']['data'] as $topic => $description) {
                    $text = 'unknown';

                    switch (gettype($description)) {
                        case 'array':
                            $text = implode('; ', $description);
                            break;
                        case 'string':
                            $text = $description;
                            break;
                    }

                    $details[] = sprintf(
                        '%s: %s',
                        $topic,
                        $text
                    );
                }
            }

            if (count($details) > 0) {
                $message = sprintf(
                    'i-doit responded with an error: %s [%s]',
                    $response['error']['message'],
                    implode('; ', $details)
                );
            } else {
                $message = sprintf(
                    'i-doit responded with an error: %s',
                    $response['error']['message']
                );
            }

            throw new RuntimeException(
                $message,
                $response['error']['code']
            );
        }

        if (!array_key_exists('result', $response)) {
            throw new RuntimeException('i-doit forgot to add a result to its response.');
        }

        return $this;
    }
764081
private function getResult($response)
    {
        $status = $response->getStatusCode();
        if ($status == 200) {
            return json_decode($response->getBody(), JSON_PRETTY_PRINT);
        } else {
            return [$status => $response->getReasonPhrase()];
        }
    }
211000
protected function handleResponse(Response $response)
    {
        $statusCode = $response->getStatusCode();

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

        return $response;
    }
1127599
protected function processTogglResponse($response)
    {
        // We only need to do something if results are paginated
        if ($response->total_count <= 50) {
            return $response->data;
        }

        $reqdata = [];
        $reqdata = json_encode($reqdata);
        $pages = ceil($response->total_count / 50);
        $curr_page = 1;
        $data = $response->data;

        $orig_uri = $this->uri;

        while ($curr_page < $pages) {
            $curr_page++;
            $this->uri .= '&page=' . $curr_page;
            $response = $this->processRequest($reqdata, self::GET);
            $this->_handleError($reqdata, $response);
            foreach ($response->data as $entry) {
                $data[] = $entry;
            }
            $this->uri = $orig_uri;
        }

        return $data;
    }
360581
protected function getResponseTransfer(array $response): ComputopApiInquireResponseTransfer
    {
        $computopApiResponseTransfer = new ComputopApiInquireResponseTransfer();
        $computopApiResponseTransfer->fromArray($response, true);
        $computopApiResponseTransfer->setHeader(
            $this->computopApiService->extractResponseHeader($response, $this->config->getInquireMethodName())
        );
        $computopApiResponseTransfer->setAmountAuth($this->computopApiService->getResponseValue($response, ComputopApiConfig::AMOUNT_AUTH));
        $computopApiResponseTransfer->setAmountCap($this->computopApiService->getResponseValue($response, ComputopApiConfig::AMOUNT_CAP));
        $computopApiResponseTransfer->setAmountCred($this->computopApiService->getResponseValue($response, ComputopApiConfig::AMOUNT_CRED));
        $computopApiResponseTransfer->setLastStatus($this->computopApiService->getResponseValue($response, ComputopApiConfig::LAST_STATUS));
        //set custom options
        $computopApiResponseTransfer->setIsAuthLast($this->isAuthLast($computopApiResponseTransfer));
        $computopApiResponseTransfer->setIsCapLast($this->isCapLast($computopApiResponseTransfer));
        $computopApiResponseTransfer->setIsCredLast($this->isCredLast($computopApiResponseTransfer));

        return $computopApiResponseTransfer;
    }