Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ResponseHandler.php
Go to the documentation of this file.
1 <?php
7 
10 
15 {
21  private static $successResponseCodes = [200, 201, 204];
22 
26  private static $phpVersionId = PHP_VERSION_ID;
27 
33  private static $failureResponses = [
34  400 => 'Bad Request - The request could not be parsed. Response: %s',
35  401 => 'Unauthorized - user is not logged in, could not be authenticated. Response: %s',
36  403 => 'Forbidden - Cannot access resource. Response: %s',
37  404 => 'Not Found - resource does not exist. Response: %s',
38  409 => 'Conflict - with state of the resource on server. Can occur with (too rapid) PUT requests. Response: %s',
39  500 => 'Server error. Response: %s'
40  ];
41 
47  private static $unexpectedResponse = 'Unexpected Signifyd API response code "%s" with content "%s".';
48 
52  private $dataDecoder;
53 
59  public function __construct(
60  DecoderInterface $dataDecoder
61  ) {
62  $this->dataDecoder = $dataDecoder;
63  }
64 
73  {
74  $responseCode = $response->getStatus();
75 
76  if (!in_array($responseCode, self::$successResponseCodes)) {
77  $errorMessage = $this->buildApiCallFailureMessage($response);
78  throw new ApiCallException($errorMessage);
79  }
80 
81  $responseBody = (string)$response->getBody();
82 
83  if (self::$phpVersionId < 70000 && empty($responseBody)) {
84  /*
85  * Only since PHP 7.0 empty string treated as JSON syntax error
86  * http://php.net/manual/en/function.json-decode.php
87  */
88  throw new ApiCallException('Response is not valid JSON: Decoding failed: Syntax error');
89  }
90 
91  try {
92  $decodedResponseBody = $this->dataDecoder->decode($responseBody);
93  } catch (\Exception $e) {
94  throw new ApiCallException(
95  'Response is not valid JSON: ' . $e->getMessage(),
96  $e->getCode(),
97  $e
98  );
99  }
100 
101  return $decodedResponseBody;
102  }
103 
110  private function buildApiCallFailureMessage(\Zend_Http_Response $response)
111  {
112  $responseBody = $response->getBody();
113 
114  if (key_exists($response->getStatus(), self::$failureResponses)) {
115  return sprintf(self::$failureResponses[$response->getStatus()], $responseBody);
116  }
117 
118  return sprintf(
119  self::$unexpectedResponse,
120  $response->getStatus(),
121  $responseBody
122  );
123  }
124 }
$response
Definition: 404.php:11