Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Pagination Example #48

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ vendor
.php-cs-fixer.cache
node_modules
package-lock.json
.phpunit.result.cache
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"gedmo/doctrine-extensions": "^3.0",
"hubspot/hubspot-php": "^5.0",
"knplabs/doctrine-behaviors": "^2.0.6",
"knplabs/knp-paginator-bundle": "^5.8",
"runroom-packages/form-handler-bundle": "^0.16",
"runroom-packages/render-event-bundle": "^0.16",
"runroom-packages/sortable-behavior-bundle": "^0.16",
Expand Down
4 changes: 2 additions & 2 deletions src/BasicEntities/Controller/BookController.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ public function __construct(BookService $service)
$this->service = $service;
}

public function books(): Response
public function books(int $page): Response
{
return $this->render('@RunroomSamples/BasicEntities/books.html.twig', [
'model' => $this->service->getBooksViewModel(),
'model' => $this->service->getBooksViewModel($page),
]);
}

Expand Down
31 changes: 29 additions & 2 deletions src/BasicEntities/Repository/BookRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\Persistence\ManagerRegistry;
use Knp\Bundle\PaginatorBundle\Pagination\SlidingPaginationInterface;
use Knp\Component\Pager\PaginatorInterface;
use Runroom\SamplesBundle\BasicEntities\Entity\Book;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
Expand All @@ -30,12 +32,17 @@
class BookRepository extends ServiceEntityRepository
{
private RequestStack $requestStack;
private PaginatorInterface $paginator;

public function __construct(ManagerRegistry $registry, RequestStack $requestStack)
{
public function __construct(
ManagerRegistry $registry,
RequestStack $requestStack,
PaginatorInterface $paginator
) {
parent::__construct($registry, Book::class);

$this->requestStack = $requestStack;
$this->paginator = $paginator;
}

public function findBySlug(string $slug): Book
Expand All @@ -55,4 +62,24 @@ public function findBySlug(string $slug): Book

return $book;
}

/**
* @phpstan-return SlidingPaginationInterface<Book>
*
* @psalm-return SlidingPaginationInterface
*/
public function getPaginatedBooks(int $page, int $limitPerPage): SlidingPaginationInterface
{
$request = $this->requestStack->getCurrentRequest() ?? new Request();

$queryBuilder = $this->createQueryBuilder('books')
->where('books.publish = true')
->leftJoin('books.translations', 'translations', Join::WITH, 'translations.locale = :locale')
->setParameter('locale', $request->getLocale());

$pagination = $this->paginator->paginate($queryBuilder, $page, $limitPerPage);
\assert($pagination instanceof SlidingPaginationInterface);

return $pagination;
}
}
8 changes: 6 additions & 2 deletions src/BasicEntities/Service/BookService.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,20 @@

class BookService
{
public const LIMIT_PER_PAGE = 6;

private BookRepository $repository;

public function __construct(BookRepository $repository)
{
$this->repository = $repository;
}

public function getBooksViewModel(): BooksViewModel
public function getBooksViewModel(int $page): BooksViewModel
{
return new BooksViewModel($this->repository->findBy(['publish' => true], ['position' => 'ASC']));
$pagination = $this->repository->getPaginatedBooks($page, self::LIMIT_PER_PAGE);

return new BooksViewModel($pagination);
}

public function getBookViewModel(string $slug): BookViewModel
Expand Down
23 changes: 15 additions & 8 deletions src/BasicEntities/ViewModel/BooksViewModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,28 +13,35 @@

namespace Runroom\SamplesBundle\BasicEntities\ViewModel;

use Knp\Bundle\PaginatorBundle\Pagination\SlidingPaginationInterface;
use Runroom\SamplesBundle\BasicEntities\Entity\Book;

class BooksViewModel
{
/**
* @var Book[]
* @phpstan-var SlidingPaginationInterface<Book>
*
* @psalm-var SlidingPaginationInterface
*/
private array $books;
protected $pagination;

/**
* @param Book[] $books
* @phpstan-param SlidingPaginationInterface<Book> $pagination
*
* @psalm-param SlidingPaginationInterface $pagination
*/
public function __construct(array $books)
public function __construct(SlidingPaginationInterface $pagination)
{
$this->books = $books;
$this->pagination = $pagination;
}

/**
* @return Book[]
* @phpstan-return SlidingPaginationInterface<Book>
*
* @psalm-return SlidingPaginationInterface
*/
public function getBooks(): array
public function getPagination(): SlidingPaginationInterface
{
return $this->books;
return $this->pagination;
}
}
6 changes: 5 additions & 1 deletion src/Resources/config/routing.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@ runroom_samples.home:

# BasicEntities
runroom_samples.basic_entities.books:
path: /books
path: /books/{page}
controller: Runroom\SamplesBundle\BasicEntities\Controller\BookController::books
defaults:
page: 1
requirements:
page: '\d+'

runroom_samples.basic_entities.book:
path: /book/{slug}
Expand Down
35 changes: 29 additions & 6 deletions src/Resources/views/BasicEntities/books.html.twig
Original file line number Diff line number Diff line change
@@ -1,10 +1,33 @@
{% extends '@RunroomSamples/base.html.twig' %}

{% block contentClass %}books-list{% endblock %}

{% block content %}
{% for book in model.books %}
<a href="{{ path('runroom_samples.basic_entities.book', {slug: book.slug}) }}">
<p>{{ book.title }}</p>
<div>{{ book.description|raw }}</div>
</a>
{% endfor %}
<div class="wrapper">
<ul class="flex flex-wrap my-10">
{% for book in model.pagination.items %}
<li class="w-1/3 rounded shadow-lg p-5 book-item no-underline">
<div class="h-40 {% if book.picture %} bg-gradient-to-r from-orange-400 via-red-500 to-pink-500{% endif %}"
>
</div>
<div class="py-5">
<div class="font-bold text-xl">{{ book.title }}</div>
<p class="text-gray-700 text-base wysiwyg">
{{ book.description|raw }}
</p>
</div>
</li>
{# <div class="book-item">
<li>
<a href="{{ path('runroom_samples.basic_entities.book', {slug: book.slug}) }}">{{book.title}}</a>
</li>
</div> #}
{% endfor %}
</ul>

<div class="flex justify-center my-10">
{% include '@RunroomSamples/pagination.html.twig' with { pagination: model.pagination } %}
</div>

</div>
{% endblock %}
41 changes: 41 additions & 0 deletions src/Resources/views/pagination.html.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{% set paginationData = pagination.paginationData %}
{% set route = app.request.attributes.get('_route') %}
{% set routeParams = app.request.attributes.get('_route_params')|merge(app.request.query.all) %}

{% if paginationData.pageCount > 1 %}
<div class="flex items-baseline flex-row">
{% if paginationData.first is defined and paginationData.current != paginationData.first %}
<span class="px-3 py-2 text-lg font-bold">
<a href="{{ path(route, routeParams|merge({'page': paginationData.first})) }}">&lt;&lt;</a>
</span>
{% endif %}

{% if paginationData.previous is defined %}
<span class="px-3 text-lg py-2">
<a rel="prev" href="{{ path(route, routeParams|merge({'page': paginationData.previous})) }}">&lt;</a>
</span>
{% endif %}

{% for page in paginationData.pagesInRange %}
{% if page != paginationData.current %}
<span class="px-3 py-2 text-lg">
<a href="{{ path(route, routeParams|merge({'page': page})) }}">{{ page }}</a>
</span>
{% else %}
<span class="px-3 py-2 text-lg font-bold">{{ page }}</span>
{% endif %}
{% endfor %}

{% if paginationData.next is defined %}
<span class="px-3 py-2 text-lg">
<a rel="next" href="{{ path(route, routeParams|merge({'page': paginationData.next})) }}">&gt;</a>
</span>
{% endif %}

{% if paginationData.last is defined and paginationData.current != paginationData.last %}
<span class="px-3 py-2 text-lg border-gray-400 font-bold">
<a href="{{ path(route, routeParams|merge({'page': paginationData.last})) }}">&gt;&gt;</a>
</span>
{% endif %}
</div>
{% endif %}
2 changes: 2 additions & 0 deletions tests/App/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
use FOS\CKEditorBundle\FOSCKEditorBundle;
use Knp\Bundle\MenuBundle\KnpMenuBundle;
use Knp\Bundle\PaginatorBundle\KnpPaginatorBundle;
use Knp\DoctrineBehaviors\DoctrineBehaviorsBundle;
use Runroom\FormHandlerBundle\RunroomFormHandlerBundle;
use Runroom\RenderEventBundle\RunroomRenderEventBundle;
Expand Down Expand Up @@ -54,6 +55,7 @@ public function registerBundles(): iterable
new FOSCKEditorBundle(),
new FrameworkBundle(),
new KnpMenuBundle(),
new KnpPaginatorBundle(),
new SecurityBundle(),
new TwigBundle(),
new SonataMediaBundle(),
Expand Down
8 changes: 5 additions & 3 deletions tests/BasicEntities/Unit/BookControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace Runroom\SamplesBundle\Tests\BasicEntities\Unit;

use Knp\Bundle\PaginatorBundle\Pagination\SlidingPaginationInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Runroom\SamplesBundle\BasicEntities\Controller\BookController;
Expand Down Expand Up @@ -54,11 +55,12 @@ protected function setUp(): void
*/
public function itRenderBooks(): void
{
$model = new BooksViewModel([]);
$model = new BooksViewModel($this->createStub(SlidingPaginationInterface::class));
$page = 1;

$this->service->method('getBooksViewModel')->willReturn($model);
$this->service->method('getBooksViewModel')->with($page)->willReturn($model);

$response = $this->controller->books();
$response = $this->controller->books($page);

static::assertSame(200, $response->getStatusCode());
}
Expand Down
11 changes: 6 additions & 5 deletions tests/BasicEntities/Unit/BookServiceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace Runroom\SamplesBundle\Tests\BasicEntities\Unit;

use Knp\Bundle\PaginatorBundle\Pagination\SlidingPaginationInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Runroom\SamplesBundle\BasicEntities\Factory\BookFactory;
Expand All @@ -34,7 +35,6 @@ class BookServiceTest extends TestCase
protected function setUp(): void
{
$this->repository = $this->createMock(BookRepository::class);

$this->service = new BookService($this->repository);
}

Expand All @@ -43,13 +43,14 @@ protected function setUp(): void
*/
public function itBuildsBooksViewModel(): void
{
$expectedBooks = [BookFactory::createOne()->object()];
$pagination = $this->createStub(SlidingPaginationInterface::class);
$page = 1;

$this->repository->method('findBy')->with(['publish' => true], ['position' => 'ASC'])->willReturn($expectedBooks);
$this->repository->method('getPaginatedBooks')->willReturn($pagination);

$model = $this->service->getBooksViewModel();
$model = $this->service->getBooksViewModel($page);

static::assertSame($model->getBooks(), $expectedBooks);
static::assertSame($model->getPagination(), $pagination);
}

/**
Expand Down