Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make the response payload accessible for derived classes. #27

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions src/Context/WebApiContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ class WebApiContext implements ApiClientAwareContext
*/
private $response;

/**
* The decoded response object.
*/
private $responsePayload;

private $placeHolders = array();

/**
Expand Down Expand Up @@ -379,4 +384,68 @@ private function getClient()

return $this->client;
}

/*
* Checks the response exists and returns it.
*
* @return Guzzle\Http\Message\Response
*/
protected function getResponse()
{
if (! $this->response) {
throw new Exception("You must first make a request to check a response.");
}
return $this->response;
}

/**
* @Then the ":arg1" header is set
*/
public function theHeaderIsSet($headerName)
{
Assertions::assertTrue(array_key_exists($headerName, $this->response->getHeaders()));
}

/**
* Return the response payload from the current response.
*
* @return mixed
*/
protected function getResponsePayload()
{
if (! $this->responsePayload) {
$json = json_decode($this->getResponse()->getBody(true));

if (json_last_error() !== JSON_ERROR_NONE) {
$message = 'Failed to decode JSON body ';

switch (json_last_error()) {
case JSON_ERROR_DEPTH:
$message .= '(Maximum stack depth exceeded).';
break;
case JSON_ERROR_STATE_MISMATCH:
$message .= '(Underflow or the modes mismatch).';
break;
case JSON_ERROR_CTRL_CHAR:
$message .= '(Unexpected control character found).';
break;
case JSON_ERROR_SYNTAX:
$message .= '(Syntax error, malformed JSON).';
break;
case JSON_ERROR_UTF8:
$message .= '(Malformed UTF-8 characters, possibly incorrectly encoded).';
break;
default:
$message .= '(Unknown error).';
break;
}

throw new \Exception($message);
}

$this->responsePayload = $json;
}

return $this->responsePayload;
}
}