This commit is contained in:
Chris
2018-10-18 15:59:38 +01:00
parent 4f6a0cb7c6
commit 380a0e8623
352 changed files with 32929 additions and 3604 deletions

View File

@@ -0,0 +1,82 @@
<?php
namespace Github\HttpClient\Message;
use Github\Exception\ApiLimitExceedException;
use Psr\Http\Message\ResponseInterface;
class ResponseMediator
{
/**
* @param ResponseInterface $response
*
* @return array|string
*/
public static function getContent(ResponseInterface $response)
{
$body = $response->getBody()->__toString();
if (strpos($response->getHeaderLine('Content-Type'), 'application/json') === 0) {
$content = json_decode($body, true);
if (JSON_ERROR_NONE === json_last_error()) {
return $content;
}
}
return $body;
}
/**
* @param ResponseInterface $response
*
* @return array|null
*/
public static function getPagination(ResponseInterface $response)
{
if (!$response->hasHeader('Link')) {
return;
}
$header = self::getHeader($response, 'Link');
$pagination = [];
foreach (explode(',', $header) as $link) {
preg_match('/<(.*)>; rel="(.*)"/i', trim($link, ','), $match);
if (3 === count($match)) {
$pagination[$match[2]] = $match[1];
}
}
return $pagination;
}
/**
* @param ResponseInterface $response
*
* @return null|string
*/
public static function getApiLimit(ResponseInterface $response)
{
$remainingCalls = self::getHeader($response, 'X-RateLimit-Remaining');
if (null !== $remainingCalls && 1 > $remainingCalls) {
throw new ApiLimitExceedException($remainingCalls);
}
return $remainingCalls;
}
/**
* Get the value for a single header.
*
* @param ResponseInterface $response
* @param string $name
*
* @return string|null
*/
public static function getHeader(ResponseInterface $response, $name)
{
$headers = $response->getHeader($name);
return array_shift($headers);
}
}