22namespace Enqueue \ElasticaBundle \Doctrine ;
33
44use Doctrine \Common \Persistence \Event \LifecycleEventArgs ;
5+ use Doctrine \ORM \Event \PostFlushEventArgs ;
56use Enqueue \ElasticaBundle \Doctrine \Queue \Commands ;
67use Enqueue \ElasticaBundle \Doctrine \Queue \SyncIndexWithObjectChangeProcessor as SyncProcessor ;
78use Enqueue \Util \JSON ;
@@ -17,6 +18,11 @@ final class SyncIndexWithObjectChangeListener implements EventSubscriber
1718 */
1819 private $ modelClass ;
1920
21+ /**
22+ * @var array
23+ */
24+ private $ scheduledForUpdateIndex = [];
25+
2026 /**
2127 * @var array
2228 */
@@ -31,23 +37,33 @@ public function __construct(Context $context, $modelClass, array $config)
3137
3238 public function postUpdate (LifecycleEventArgs $ args )
3339 {
34-
3540 if ($ args ->getObject () instanceof $ this ->modelClass ) {
36- $ this ->sendUpdateIndexMessage ( SyncProcessor::UPDATE_ACTION , $ args) ;
41+ $ this ->scheduledForUpdateIndex [] = [ ' action ' => SyncProcessor::UPDATE_ACTION , ' args ' => $ args] ;
3742 }
3843 }
3944
4045 public function postPersist (LifecycleEventArgs $ args )
4146 {
4247 if ($ args ->getObject () instanceof $ this ->modelClass ) {
43- $ this ->sendUpdateIndexMessage ( SyncProcessor::INSERT_ACTION , $ args) ;
48+ $ this ->scheduledForUpdateIndex [] = [ ' action ' => SyncProcessor::INSERT_ACTION , ' args ' => $ args] ;
4449 }
4550 }
4651
4752 public function preRemove (LifecycleEventArgs $ args )
4853 {
4954 if ($ args ->getObject () instanceof $ this ->modelClass ) {
50- $ this ->sendUpdateIndexMessage (SyncProcessor::REMOVE_ACTION , $ args );
55+ $ this ->scheduledForUpdateIndex [] = ['action ' => SyncProcessor::REMOVE_ACTION , 'args ' => $ args ];
56+ }
57+ }
58+
59+ public function postFlush (PostFlushEventArgs $ event )
60+ {
61+ if (count ($ this ->scheduledForUpdateIndex )) {
62+ foreach ($ this ->scheduledForUpdateIndex as $ updateIndex ) {
63+ $ this ->sendUpdateIndexMessage ($ updateIndex ['action ' ], $ updateIndex ['args ' ]);
64+ }
65+
66+ $ this ->scheduledForUpdateIndex = [];
5167 }
5268 }
5369
@@ -57,6 +73,7 @@ public function getSubscribedEvents()
5773 'postPersist ' ,
5874 'postUpdate ' ,
5975 'preRemove ' ,
76+ 'postFlush '
6077 ];
6178 }
6279
0 commit comments