Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

64 lines
1.8KB

  1. <?php
  2. namespace Lc\SovBundle\EventSubscriber;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Lc\SovBundle\Doctrine\EntityInterface;
  5. use Lc\SovBundle\Doctrine\Extension\SortableInterface;
  6. use Lc\SovBundle\Doctrine\Extension\StatusInterface;
  7. use Lc\SovBundle\Doctrine\Extension\TreeInterface;
  8. use Lc\SovBundle\Event\EntityManager\EntityManagerEvent;
  9. use Lc\SovBundle\Repository\AbstractRepositoryInterface;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. class SortablePropertyEventSubscriber implements EventSubscriberInterface
  12. {
  13. protected $em;
  14. protected $adminUrlGenerator;
  15. public function __construct(EntityManagerInterface $entityManager)
  16. {
  17. $this->em = $entityManager;
  18. }
  19. public static function getSubscribedEvents()
  20. {
  21. return [
  22. EntityManagerEvent::PRE_CREATE_EVENT => ['setCommonProperty'],
  23. ];
  24. }
  25. public function setCommonProperty(EntityManagerEvent $event)
  26. {
  27. $entity = $event->getEntity();
  28. $entityRepository = $this->em->getRepository(get_class($entity));
  29. if ($entity instanceof SortableInterface) {
  30. $this->setSortableProperty($entity, $entityRepository);
  31. }
  32. }
  33. private function setSortableProperty(EntityInterface $entity, AbstractRepositoryInterface $entityRepository)
  34. {
  35. $countParam = array();
  36. if ($entity instanceof StatusInterface) {
  37. $countParam['status'] = 1;
  38. }
  39. if ($entity instanceof TreeInterface) {
  40. if ($entity->getParent()) {
  41. $countParam['parent'] = $entity->getParent()->getId();
  42. } else {
  43. $countParam['parent'] = null;
  44. }
  45. }
  46. $total = $entityRepository->count($countParam);
  47. $entity->setPosition($total);
  48. }
  49. }