<?php
/**
* @copyright Copyright (C) Ibexa AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
declare(strict_types=1);
namespace Ibexa\Bundle\OrderManagement\PageBuilder\Orders;
use Ibexa\Contracts\OrderManagement\OrderServiceInterface;
use Ibexa\FieldTypePage\FieldType\Page\Block\Renderer\BlockRenderEvents;
use Ibexa\FieldTypePage\FieldType\Page\Block\Renderer\Event\PreRenderEvent;
use Ibexa\FieldTypePage\FieldType\Page\Block\Renderer\Twig\TwigRenderRequest;
use Ibexa\OrderManagement\Pagerfanta\Adapter\OrderListAdapter;
use Pagerfanta\Pagerfanta;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
final class BlockSubscriber implements EventSubscriberInterface
{
private const PAGINATION_PAGE_PARAM_PREFIX = 'page_';
private const PAGINATION_DEFAULT_LIMIT = 10;
private const PAGINATION_DEFAULT_CURRENT_PAGE = 1;
private OrderServiceInterface $orderService;
private RequestStack $requestStack;
private QueryFactoryInterface $queryFactory;
public function __construct(
OrderServiceInterface $orderService,
RequestStack $requestStack,
QueryFactoryInterface $queryFactory
) {
$this->orderService = $orderService;
$this->requestStack = $requestStack;
$this->queryFactory = $queryFactory;
}
public static function getSubscribedEvents(): array
{
return [
BlockRenderEvents::getBlockPreRenderEventName(Block::BLOCK_IDENTIFIER) => 'onPreRender',
];
}
public function onPreRender(PreRenderEvent $event): void
{
$request = $event->getRenderRequest();
if ($request instanceof TwigRenderRequest) {
$block = new Block($event->getBlockValue());
$query = $this->queryFactory->createQuery($block);
$pagerfanta = new Pagerfanta(new OrderListAdapter($this->orderService, $query));
$pagerfanta->setCurrentPage($this->getCurrentPage(self::PAGINATION_PAGE_PARAM_PREFIX . $block->getId()));
$pagerfanta->setMaxPerPage($block->getLimit() ?? self::PAGINATION_DEFAULT_LIMIT);
$request->addParameter('columns', $block->getColumns());
$request->addParameter('orders', $pagerfanta);
}
}
private function getCurrentPage(string $pageParam): int
{
$request = $this->requestStack->getMainRequest();
if ($request === null) {
return self::PAGINATION_DEFAULT_CURRENT_PAGE;
}
return $request->query->getInt($pageParam, self::PAGINATION_DEFAULT_CURRENT_PAGE);
}
}