|
13 | 13 | */ |
14 | 14 | class DocumentFactory implements DocumentFactoryInterface |
15 | 15 | { |
| 16 | + /** |
| 17 | + * Create a new document factory instance. |
| 18 | + */ |
| 19 | + public function __construct( |
| 20 | + protected bool $softDelete = false, |
| 21 | + ) {} |
| 22 | + |
16 | 23 | /** |
17 | 24 | * Create OpenSearch documents from the given model collection. |
18 | 25 | */ |
19 | 26 | public function makeFromModels(Collection $models): Collection |
20 | 27 | { |
21 | 28 | return $models->map(function (Model $model) { |
22 | | - if ( |
23 | | - config('scout.soft_delete', false) && |
24 | | - in_array(SoftDeletes::class, class_uses_recursive($model), true) |
25 | | - ) { |
| 29 | + if ($this->softDelete && $this->isSoftDeletable($model)) { |
26 | 30 | $model->pushSoftDeleteMetadata(); |
27 | 31 | } |
28 | 32 |
|
29 | | - $documentId = (string) $model->getScoutKey(); |
30 | | - $documentContent = array_merge($model->scoutMetadata(), $model->toSearchableArray()); |
| 33 | + $source = $this->makeDocumentSource($model); |
31 | 34 |
|
32 | | - if (array_key_exists('_id', $documentContent)) { |
33 | | - throw new UnexpectedValueException(sprintf( |
34 | | - '_id is not allowed in the document content. Please, make sure the field is not returned by '. |
35 | | - 'the %1$s::toSearchableArray or %1$s::scoutMetadata methods.', |
36 | | - class_basename($model) |
37 | | - )); |
38 | | - } |
| 35 | + $this->assertValidDocumentSource($model, $source); |
39 | 36 |
|
40 | | - return new Document($documentId, $documentContent); |
| 37 | + return new Document((string) $model->getScoutKey(), $source); |
41 | 38 | }); |
42 | 39 | } |
| 40 | + |
| 41 | + /** |
| 42 | + * Assert that the given document source is valid. |
| 43 | + * |
| 44 | + * @throws \UnexpectedValueException |
| 45 | + */ |
| 46 | + protected function assertValidDocumentSource(Model $model, array $source): void |
| 47 | + { |
| 48 | + if (array_key_exists('_id', $source)) { |
| 49 | + throw new UnexpectedValueException(sprintf( |
| 50 | + '_id is not allowed in the document source. Please, make sure the field is not returned by '. |
| 51 | + 'the %1$s::toSearchableArray or %1$s::scoutMetadata methods.', |
| 52 | + class_basename($model) |
| 53 | + )); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Create the document source from the given model. |
| 59 | + */ |
| 60 | + protected function makeDocumentSource(Model $model): array |
| 61 | + { |
| 62 | + return array_merge( |
| 63 | + $model->scoutMetadata(), |
| 64 | + $model->toSearchableArray() |
| 65 | + ); |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Determine if the given model uses soft deletes. |
| 70 | + */ |
| 71 | + protected function isSoftDeletable(Model $model): bool |
| 72 | + { |
| 73 | + return in_array(SoftDeletes::class, class_uses_recursive($model), true); |
| 74 | + } |
43 | 75 | } |
0 commit comments