Skip to content
This repository was archived by the owner on Sep 12, 2024. It is now read-only.
Open
Show file tree
Hide file tree
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
6 changes: 5 additions & 1 deletion src/Duffel/Api/AbstractApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ abstract class AbstractApi {
*/
private $client;

/**
* @var int|null
*/
private $limit;

/**
*
* @param Client $client
Expand Down Expand Up @@ -123,7 +128,6 @@ protected function delete(string $uri, array $params = [], array $headers = [])
return ResponseParser::getContent($response);
}


/**
* @param string $uri
*
Expand Down
19 changes: 19 additions & 0 deletions src/Duffel/HttpClient/ResponseParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,25 @@ public static function getContent(ResponseInterface $response) {
return $body;
}

/**
* @param ResponseInterface $response
*
* @return array<string,string>
*/
public static function getPagination(ResponseInterface $response): array {
$body = (string) $response->getBody();

if (!\in_array($body, ['', 'null', 'true', 'false'], true) && 0 === \strpos($response->getHeaderLine(self::CONTENT_TYPE_HEADER), self::JSON_CONTENT_TYPE)) {
$decoded = JsonArray::decode($body);

if (array_key_exists('meta', $decoded)) {
return $decoded['meta'];
}
}

return [];
}

private static function getHeader(ResponseInterface $response, string $name): ?string {
$headers = $response->getHeader($name);

Expand Down
183 changes: 183 additions & 0 deletions src/Duffel/ResultPager.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
<?php

declare(strict_types=1);

namespace Duffel;

use Closure;
use Generator;
use Duffel\Api\AbstractApi;
use Duffel\Exception\RuntimeException;
use Duffel\HttpClient\ResponseParser;
use ValueError;

final class ResultPager implements ResultPagerInterface {
/**
* @var int
*/
private const DEFAULT_LIMIT = 50;

/**
* @var Client
*/
private $client;

/**
* @var int
*/
private $limit;

/**
* @var array<string,string>
*/
private $pagination;

/**
* @param Client $client
* @param int|null $limit
*
* @return void
*/
public function __construct(Client $client, int $limit = null) {
if (null !== $limit && ($limit < 1 || $limit > 200)) {
throw new ValueError(\sprintf('%s::__construct(): Argument #2 ($limit) must be between 1 and 200, or null', self::class));
}

$this->client = $client;
$this->limit = $limit ?? self::DEFAULT_LIMIT;
$this->pagination = [];
}

/**
* @param AbstractApi $api
* @param string $method
* @param array $parameters
*
* @throws \Http\Client\Exception
*
* @return array
*/
public function fetch(AbstractApi $api, string $method, array $parameters = []): array
{
$result = self::bindPerPage($api, $this->limit)->$method(...$parameters);

if (!\is_array($result)) {
throw new RuntimeException('Pagination of this endpoint is not supported.');
}

return $result;
}

/**
* @param AbstractApi $api
* @param string $method
* @param array $parameters
*
* @throws \Http\Client\Exception
*
* @return array
*/
public function fetchAll(AbstractApi $api, string $method, array $parameters = []): array
{
return \iterator_to_array($this->fetchAllLazy($api, $method, $parameters));
}

/**
* @param AbstractApi $api
* @param string $method
* @param array $parameters
*
* @throws \Http\Client\Exception
*
* @return \Generator
*/
public function fetchAllLazy(AbstractApi $api, string $method, array $parameters = []): Generator {
/** @var mixed $value */
foreach ($this->fetch($api, $method, $parameters) as $value) {
yield $value;
}

while ($this->hasAfter()) {
/** @var mixed $value */
foreach ($this->fetchAfter() as $value) {
yield $value;
}
}
}

/**
* @return bool
*/
public function hasAfter(): bool {
return isset($this->pagination['after']);
}

/**
* @throws \Http\Client\Exception
*
* @return array
*/
public function fetchAfter(): array {
return $this->get('after');
}

/**
* @return bool
*/
public function hasBefore(): bool {
return isset($this->pagination['before']);
}

/**
* @throws \Http\Client\Exception
*
* @return array
*/
public function fetchBefore(): array {
return $this->get('before');
}

/**
* @param string $key
*
* @throws \Http\Client\Exception
*
* @return array
*/
private function get(string $key): array {
$pagination = $this->pagination[$key] ?? null;

if (null === $pagination) {
return [];
}

$result = $this->client->getHttpClient()->get($pagination);

$content = ResponseParser::getContent($result);

if (!\is_array($content)) {
throw new RuntimeException('Pagination of this endpoint is not supported.');
}

return $content;
}

/**
* @param AbstractApi $api
* @param int $limit
*
* @return AbstractApi
*/
private static function bindPerPage(AbstractApi $api, int $limit): AbstractApi {
$closure = Closure::bind(static function (AbstractApi $api) use ($limit): AbstractApi {
$clone = clone $api;

$clone->limit = $limit;

return $clone;
}, null, AbstractApi::class);

/** @var AbstractApi */
return $closure($api);
}
}
67 changes: 67 additions & 0 deletions src/Duffel/ResultPagerInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

declare(strict_types=1);

namespace Duffel;

use Generator;
use Duffel\Api\AbstractApi;

interface ResultPagerInterface {
/**
* @param AbstractApi $api
* @param string $method
* @param array $parameters
*
* @throws \Http\Client\Exception
*
* @return array
*/
public function fetch(AbstractApi $api, string $method, array $parameters = []): array;

/**
* @param AbstractApi $api
* @param string $method
* @param array $parameters
*
* @throws \Http\Client\Exception
*
* @return array
*/
public function fetchAll(AbstractApi $api, string $method, array $parameters = []): array;

/**
* @param AbstractApi $api
* @param string $method
* @param array $parameters
*
* @throws \Http\Client\Exception
*
* @return \Generator
*/
public function fetchAllLazy(AbstractApi $api, string $method, array $parameters = []): Generator;

/**
* @return bool
*/
public function hasAfter(): bool;

/**
* @throws \Http\Client\Exception
*
* @return array
*/
public function fetchAfter(): array;

/**
* @return bool
*/
public function hasBefore(): bool;

/**
* @throws \Http\Client\Exception
*
* @return array
*/
public function fetchBefore(): array;
}
40 changes: 40 additions & 0 deletions tests/Duffel/HttpClient/ResponseParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -183,4 +183,44 @@ public function testGetErrorMessageWhenJsonIsObjectWithoutErrorsKeyReturnsNull()

$this->assertSame(null, ResponseParser::getErrorMessage($this->stub));
}

public function testGetPaginationAsJsonWithMetaKey(): void {
$this->stub->method('getBody')
->willReturn('{"data": {"some": {"keys": ["with", "values"]} }, "meta": {"after": "some-after-key", "before": "some-before-key", "limit": 50} }');
$this->stub->method('getHeaderLine')
->with('Content-Type')
->willReturn('application/json');

$this->assertSame(["after" => "some-after-key", "before" => "some-before-key", "limit" => 50], ResponseParser::getPagination($this->stub));
}

public function testGetPaginationAsJsonWithMetaKeyAndNullAfter(): void {
$this->stub->method('getBody')
->willReturn('{"data": {"some": {"keys": ["with", "values"]} }, "meta": {"after": null, "before": "some-before-key", "limit": 50} }');
$this->stub->method('getHeaderLine')
->with('Content-Type')
->willReturn('application/json');

$this->assertSame(["after" => null, "before" => "some-before-key", "limit" => 50], ResponseParser::getPagination($this->stub));
}

public function testGetPaginationAsJsonWithMetaKeyAndNullBefore(): void {
$this->stub->method('getBody')
->willReturn('{"data": {"some": {"keys": ["with", "values"]} }, "meta": {"after": "some-after-key", "before": null, "limit": 50} }');
$this->stub->method('getHeaderLine')
->with('Content-Type')
->willReturn('application/json');

$this->assertSame(["after" => "some-after-key", "before" => null, "limit" => 50], ResponseParser::getPagination($this->stub));
}

public function testGetPaginationAsJsonWithoutMetaKey(): void {
$this->stub->method('getBody')
->willReturn('{"data": {"some": {"keys": ["with", "values"]} } }');
$this->stub->method('getHeaderLine')
->with('Content-Type')
->willReturn('application/json');

$this->assertSame([], ResponseParser::getPagination($this->stub));
}
}