Skip to content

Commit

Permalink
Update Client to be able to handle responses with PDF
Browse files Browse the repository at this point in the history
  • Loading branch information
slavcodev committed Dec 9, 2015
1 parent c9cca54 commit 13d9cf7
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use BadMethodCallException;
use Rebilly\Http\CurlHandler;
use Rebilly\Middleware\LogHandler;
use Rebilly\Rest\File;
use RuntimeException;
use InvalidArgumentException;
use Psr\Http\Message\RequestInterface as Request;
Expand Down Expand Up @@ -401,6 +402,33 @@ public function send($method, $payload, $path, $params = [], array $headers = []
return null;
}

$responseParsers = [
'application/json' => [$this, 'parseJson'],
'application/pdf' => [$this, 'parsePdf'],
];

if (preg_match('/^(\w+\/\w+).*/i', $response->getHeaderLine('Content-Type'), $matches)) {
$contentType = $matches[1];
} else {
$contentType = 'application/json';
}

if (!isset($responseParsers[$contentType])) {
throw new InvalidArgumentException('Unsupported response');
}

return call_user_func($responseParsers[$contentType], $request, $response, $contentType);
}

/**
* @param Request $request
* @param Response $response
* @param string $type
*
* @return mixed
*/
protected function parseJson(Request $request, Response $response, $type)
{
// Find resource type (URL) in response location or request url
$location = $response->hasHeader('Location')
? $this->createUri($response->getHeaderLine('Location'))
Expand Down Expand Up @@ -438,6 +466,20 @@ public function send($method, $payload, $path, $params = [], array $headers = []
return $resource;
}

/**
* @param Request $request
* @param Response $response
* @param string $type
*
* @return File
*/
protected function parsePdf(Request $request, Response $response, $type)
{
$body = $response->getBody();

return new File($type, (string) $body, $body->getSize());
}

/**
* Factory method to create a new Request object.
*
Expand Down

0 comments on commit 13d9cf7

Please sign in to comment.