@@ -53,7 +53,8 @@ public function __construct(
5353 private readonly string $ event ,
5454 private readonly string $ modelClass ,
5555 private readonly string $ keyName ,
56- private readonly mixed $ keyValue
56+ private readonly mixed $ keyValue ,
57+ private readonly string $ elasticsearchId ,
5758 ) {
5859 $ this ->onConnection (config ('elastica-bridge.connection ' ));
5960 }
@@ -63,10 +64,18 @@ public function handle(): void
6364 $ model = $ this ->modelClass ::query ()->where ($ this ->keyName , $ this ->keyValue )->first ();
6465
6566 if (! $ model instanceof ElasticsearchableInterface || ! $ model instanceof Model) {
67+ foreach ($ this ->matchingIndicesForElement () as $ index ) {
68+ if (! $ index ->getElasticaIndex ()->exists ()) {
69+ continue ;
70+ }
71+
72+ $ this ->ensureModelMissingFromIndex ($ index );
73+ }
74+
6675 return ;
6776 }
6877
69- foreach ($ this ->matchingIndicesForElement ($ model ) as $ index ) {
78+ foreach ($ this ->matchingIndicesForElement () as $ index ) {
7079 if (! $ index ->getElasticaIndex ()->exists ()) {
7180 continue ;
7281 }
@@ -79,7 +88,7 @@ public function handle(): void
7988
8089 $ shouldBePresent
8190 ? $ this ->ensureModelPresentInIndex ($ index , $ model )
82- : $ this ->ensureModelMissingFromIndex ($ index, $ model );
91+ : $ this ->ensureModelMissingFromIndex ($ index );
8392 }
8493 }
8594
@@ -89,23 +98,22 @@ private function ensureModelPresentInIndex(IndexInterface $index, Model $model):
8998 $ index ->getElasticaIndex ()->addDocument ($ model ->toElasticaDocument ($ index ));
9099 }
91100
92- /** @param ElasticsearchableInterface&Model $model */
93- private function ensureModelMissingFromIndex (IndexInterface $ index , Model $ model ): void
101+ private function ensureModelMissingFromIndex (IndexInterface $ index ): void
94102 {
95103 try {
96- $ index ->getElasticaIndex ()->deleteById ($ model -> getElasticsearchId () );
104+ $ index ->getElasticaIndex ()->deleteById ($ this -> elasticsearchId );
97105 } catch (ClientResponseException ) {
98106 }
99107 }
100108
101109 /**
102110 * @return IndexInterface[]
103111 */
104- public function matchingIndicesForElement (Model $ model ): array
112+ public function matchingIndicesForElement (): array
105113 {
106114 return array_filter (
107115 app (IndexRepository::class)->all (),
108- fn (IndexInterface $ index ): bool => in_array ($ model ::class , $ index ->getAllowedDocuments (), true )
116+ fn (IndexInterface $ index ): bool => in_array ($ this -> modelClass , $ index ->getAllowedDocuments (), true )
109117 );
110118 }
111119}
0 commit comments