<?php
/**
* Created by simpson <simpsonwork@gmail.com>
* Date: 2019-04-18
* Time: 20:53
*/
namespace App\EventSubscriber;
use App\Entity\Profile\Profile;
use App\Event\PaginatorPageTakenEvent;
use App\Event\Profile\ProfilesShownEvent;
use App\Repository\ReadModel\ProfileListingReadModel;
use App\Service\DefaultCityProvider;
use Carbon\CarbonImmutable;
use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
use Knp\Component\Pager\Event\AfterEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class PaginationSubscriber implements EventSubscriberInterface
{
public function __construct(
protected DefaultCityProvider $defaultCityProvider,
private EventDispatcherInterface $eventDispatcher
) {}
public function changeRoute(AfterEvent $event): void
{
$paginationView = $event->getPaginationView();
if (!$paginationView instanceof SlidingPagination) {
return;
}
$currentRoute = $paginationView->getRoute();
if (false !== strpos($currentRoute, '._pagination')) {
$paginationView->setUsedRoute(str_replace('._pagination', '', $currentRoute));
}
if ('homepage' === $currentRoute) {
$paginationView->setUsedRoute('profile_list.list_by_city');
$paginationView->setParam('city', $this->defaultCityProvider->getDefaultCity()->getUriIdentity());
}
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents()
{
return [
PaginatorPageTakenEvent::NAME => 'onPaginatorPageTaken',
'knp_pager.after' => 'changeRoute',
];
}
public function onPaginatorPageTaken(PaginatorPageTakenEvent $event): void
{
//вынесено d ProfileCtrController для ajax
return;
$items = $event->getItems();
if(empty($items))
return;
if($items[0] instanceof Profile) {
$profileIds = array_map(function(Profile $profile): int {
return $profile->getId();
}, $items);
$this->eventDispatcher->dispatch(new ProfilesShownEvent($profileIds, 'pagination_profiles'), ProfilesShownEvent::NAME);
} elseif($items[0] instanceof ProfileListingReadModel) {
$profileIds = array_map(function(ProfileListingReadModel $profileListingReadModel) {
return $profileListingReadModel->id;
}, $items);
$this->eventDispatcher->dispatch(new ProfilesShownEvent($profileIds, 'pagination_profiles_read_model'), ProfilesShownEvent::NAME);
}
}
}