API V1 response modified. Pager metadata added.

This commit is contained in:
Alexey Skobkin 2018-06-23 16:08:23 +03:00
parent 81eb903d21
commit fb8d62f991
2 changed files with 91 additions and 1 deletions

View file

@ -3,6 +3,7 @@
namespace App\Api\V1\Controller; namespace App\Api\V1\Controller;
use App\Api\V1\DTO\ApiResponse; use App\Api\V1\DTO\ApiResponse;
use App\Api\V1\DTO\ListPage;
use App\Entity\Torrent; use App\Entity\Torrent;
use App\Repository\TorrentRepository; use App\Repository\TorrentRepository;
use Pagerfanta\Adapter\DoctrineORMAdapter; use Pagerfanta\Adapter\DoctrineORMAdapter;
@ -28,7 +29,7 @@ class TorrentController extends Controller
->setMaxPerPage(self::PER_PAGE) ->setMaxPerPage(self::PER_PAGE)
; ;
return $this->json(new ApiResponse($pager->getCurrentPageResults()),Response::HTTP_OK, [], [ return $this->json(new ApiResponse(ListPage::createFromPager($pager)),Response::HTTP_OK, [], [
'groups' => array_merge(self::DEFAULT_SERIALIZER_GROUPS,['api_v1_search']), 'groups' => array_merge(self::DEFAULT_SERIALIZER_GROUPS,['api_v1_search']),
]); ]);
} }

View file

@ -0,0 +1,89 @@
<?php
namespace App\Api\V1\DTO;
use Pagerfanta\Pagerfanta;
use Symfony\Component\Serializer\Annotation as Serializer;
class ListPage
{
/**
* @var int
*
* @Serializer\Groups({"api_v1"})
*/
private $numberOfPages;
/**
* @var int
*
* @Serializer\Groups({"api_v1"})
*/
private $currentPage;
/**
* @var int
*
* @Serializer\Groups({"api_v1"})
*/
private $numberOfResults;
/**
* @var int
*
* @Serializer\Groups({"api_v1"})
*/
private $maxPerPage;
/**
* @var \Traversable
*
* @Serializer\Groups({"api_v1"})
*/
protected $items;
public function __construct(\Traversable $items, int $numberOfResults, int $numberOfPages, int $currentPage, int $maxPerPage)
{
$this->items = $items;
$this->numberOfResults = $numberOfResults;
$this->numberOfPages = $numberOfPages;
$this->currentPage = $currentPage;
$this->maxPerPage = $maxPerPage;
}
public static function createFromPager(Pagerfanta $pager): self
{
return new static(
$pager->getCurrentPageResults(),
$pager->getNbResults(),
$pager->getNbPages(),
$pager->getCurrentPage(),
$pager->getMaxPerPage()
);
}
public function getNumberOfPages(): int
{
return $this->numberOfPages;
}
public function getCurrentPage(): int
{
return $this->currentPage;
}
public function getNumberOfResults(): int
{
return $this->numberOfResults;
}
public function getMaxPerPage(): int
{
return $this->maxPerPage;
}
public function getItems(): \Traversable
{
return $this->items;
}
}