<?php
namespace Roothirsch\CoreBundle\Behaviors\DragDropSortable;
use ApiPlatform\Core\EventListener\EventPriorities;
use Roothirsch\CoreBundle\Admin\Field\DragDropPositionField;
use Doctrine\Common\Annotations\Reader;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Collection\EntityCollection;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterCrudActionEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
use Gedmo\Mapping\Annotation\SortableGroup;
use Gedmo\Mapping\Annotation\SortablePosition;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\PropertyAccess\PropertyAccess;
class DragDropSortableSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
protected $entityManager;
/**
* @var Reader
*/
protected $reader;
public function __construct(EntityManagerInterface $entityManager, Reader $reader)
{
$this->entityManager = $entityManager;
$this->reader = $reader;
}
public static function getSubscribedEvents()
{
return [
AfterCrudActionEvent::class => ['processGroups']
];
}
public function processGroups(AfterCrudActionEvent $event)
{
$context = $event->getAdminContext();
$responseParameters = $event->getResponseParameters();
$metadata = $this->entityManager->getMetadataFactory()->getMetadataFor($context->getEntity()->getFqcn());
$positionProperty = null;
$groupProperty = null;
foreach($metadata->getReflectionClass()->getProperties() as $property) {
if ($this->reader->getPropertyAnnotation($property, SortablePosition::class) instanceof SortablePosition) {
$positionProperty = $property;
}
if ($this->reader->getPropertyAnnotation($property, SortableGroup::class) instanceof SortableGroup) {
$groupProperty = $property;
}
}
if ($groupProperty !== null && $responseParameters->has('entities')) {
$propertyAccessor = PropertyAccess::createPropertyAccessor();
$groups = [];
/** @var EntityDto $entityDto */
foreach($responseParameters->get('entities') as $entityDto) {
$group = $propertyAccessor->getValue($entityDto->getInstance(), $groupProperty->getName());
if (!isset($groups[$group->getId()])) {
$groups[$group->getId()] = [
'group' => $group,
'entites' => []
];
}
$groups[$group->getId()]['entities'][] = $entityDto;
}
usort($groups, function($a, $b) {
return $a['group']->getPosition() > $b['group']->getPosition();
});
$responseParameters->set('groups', $groups);
}
}
}