| 1 | <?php |
||
| 9 | class UniqueStateAbleListener implements EventSubscriber |
||
| 10 | { |
||
| 11 | /** |
||
| 12 | * {@inheritdoc} |
||
| 13 | */ |
||
| 14 | public function postPersist(LifecycleEventArgs $event) |
||
| 15 | { |
||
| 16 | $object = $event->getObject(); |
||
| 17 | |||
| 18 | if ($object instanceof UniqueStateAbleInterface && $object->getUniqueState()) { |
||
| 19 | // with this approach `entities` will not take there's events. |
||
| 20 | $em = $event->getEntityManager(); |
||
| 21 | $id = $em->getClassMetadata(get_class($object))->identifier[0]; |
||
| 22 | |||
| 23 | $em->createQueryBuilder() |
||
| 24 | ->update(get_class($object), 'o') |
||
| 25 | ->set('o.' . $object->getUniqueStateField(), ':update') |
||
| 26 | ->where('o.' . $object->getUniqueStateField() . ' = :where') |
||
| 27 | ->andWhere('o.' . $id . ' <> :self') |
||
| 28 | ->setParameter('update', false) |
||
| 29 | ->setParameter('where', true) |
||
| 30 | ->setParameter('self', $object) |
||
| 31 | ->getQuery()->execute() |
||
| 32 | ; |
||
| 33 | } |
||
| 34 | } |
||
| 35 | |||
| 36 | /** |
||
| 37 | * {@inheritdoc} |
||
| 38 | */ |
||
| 39 | public function postUpdate(LifecycleEventArgs $event) |
||
| 43 | |||
| 44 | /** |
||
| 45 | * {@inheritdoc} |
||
| 46 | */ |
||
| 47 | public function getSubscribedEvents() |
||
| 54 | } |
||
| 55 |