diff --git a/src/Object/PaginationLink.php b/src/Object/PaginationLink.php new file mode 100644 index 0000000..00c569a --- /dev/null +++ b/src/Object/PaginationLink.php @@ -0,0 +1,23 @@ +; rel=\"(next|previous)\"/', $item, $match)) { + $this->{$match[2]} = $match[1]; + } + } + } +} diff --git a/src/Service/AbstractService.php b/src/Service/AbstractService.php index 6efe4e5..2550e77 100644 --- a/src/Service/AbstractService.php +++ b/src/Service/AbstractService.php @@ -6,6 +6,7 @@ use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use Shopify\ApiInterface; +use Shopify\Object\PaginationLink; abstract class AbstractService { @@ -106,4 +107,13 @@ function ($object) use ($className) { }, $data ); } + + /** [fetch pagination link from Shopify Link headers] + * supported only in api version 2019-07 of the API and above + * @return PaginationLink + */ + public function getPaginationLink(): PaginationLink + { + return new PaginationLink($this->getLastResponse()->getHeaderLine('Link')); + } } diff --git a/test/Service/PaginationLinkTest.php b/test/Service/PaginationLinkTest.php new file mode 100644 index 0000000..5c1821d --- /dev/null +++ b/test/Service/PaginationLinkTest.php @@ -0,0 +1,41 @@ +getApiMock( + ['customers' => ['unit test']], + ['Link' => '<' . $previous . '>; rel="previous", <' . $next . '>; rel="next"'] + ); + + $service = new CustomerService($api); + $service->all(); + $res = $service->getPaginationLink(); + $this->assertInstanceOf(PaginationLink::class, $res); + $this->assertTrue($res->next == $next); + $this->assertTrue($res->previous == $previous); + + // test only next + $api = $this->getApiMock( + ['customers' => ['unit test']], + ['Link' => '<' . $next . '>; rel="next"'] + ); + + $service = new CustomerService($api); + $service->all(); + $res = $service->getPaginationLink(); + $this->assertInstanceOf(PaginationLink::class, $res); + $this->assertTrue($res->next == $next); + } +} diff --git a/test/TestCase.php b/test/TestCase.php index 858b7be..4b6d784 100644 --- a/test/TestCase.php +++ b/test/TestCase.php @@ -20,7 +20,7 @@ public function getApi(array $params = array()) return $api; } - public function getApiMock($file) + public function getApiMock($file, array $headers = ['X-Foo' => 'Bar']) { $json = null; if (is_array($file)) { @@ -33,7 +33,7 @@ public function getApiMock($file) } $json = file_get_contents($path); } - $mock = new MockHandler([new Response(200, ['X-Foo' => 'Bar'], $json)]); + $mock = new MockHandler([new Response(200, $headers, $json)]); $handler = HandlerStack::create($mock); $client = new Client(['handler' => $handler]);