File tree 2 files changed +62
-7
lines changed 2 files changed +62
-7
lines changed Original file line number Diff line number Diff line change 18
18
use Tequila \MongoDB \Traits \ResolveReadWriteOptionsTrait ;
19
19
use Tequila \MongoDB \Write \Model \DeleteMany ;
20
20
use Tequila \MongoDB \Write \Model \DeleteOne ;
21
+ use Tequila \MongoDB \Write \Model \InsertMany ;
21
22
use Tequila \MongoDB \Write \Model \InsertOne ;
22
23
use Tequila \MongoDB \Write \Model \ReplaceOne ;
23
24
use Tequila \MongoDB \Write \Model \UpdateMany ;
@@ -427,13 +428,8 @@ public function getNamespace()
427
428
*/
428
429
public function insertMany ($ documents , array $ options = [])
429
430
{
430
- $ models = [];
431
-
432
- foreach ($ documents as $ document ) {
433
- $ models [] = new InsertOne ($ document );
434
- }
435
-
436
- $ bulkWriteResult = $ this ->bulkWrite ($ models , $ options );
431
+ $ writeModel = new InsertMany ($ documents );
432
+ $ bulkWriteResult = $ this ->bulkWrite ([$ writeModel ], $ options );
437
433
438
434
return new InsertManyResult ($ bulkWriteResult );
439
435
}
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ namespace Tequila \MongoDB \Write \Model ;
4
+
5
+ use Tequila \MongoDB \BulkWrite ;
6
+ use Tequila \MongoDB \Exception \InvalidArgumentException ;
7
+ use Tequila \MongoDB \WriteModelInterface ;
8
+ use function Tequila \MongoDB \ensureValidDocument ;
9
+ use function Tequila \MongoDB \getType ;
10
+
11
+ class InsertMany implements WriteModelInterface
12
+ {
13
+ /**
14
+ * @var array
15
+ */
16
+ private $ documents = [];
17
+
18
+ /**
19
+ * @param array $documents
20
+ */
21
+ public function __construct (array $ documents )
22
+ {
23
+ foreach ($ documents as $ position => $ document ) {
24
+ if (!is_array ($ document ) && !is_object ($ document )) {
25
+ throw new InvalidArgumentException (
26
+ sprintf (
27
+ 'Each document must be an array or an object, %s given in $documents[%s]. ' ,
28
+ getType ($ document ),
29
+ $ position
30
+ )
31
+ );
32
+ }
33
+
34
+ try {
35
+ ensureValidDocument ($ document );
36
+ } catch (InvalidArgumentException $ e ) {
37
+ throw new InvalidArgumentException (
38
+ sprintf (
39
+ 'Invalid document at $documents[%s]: %s ' ,
40
+ $ position ,
41
+ $ e ->getMessage ()
42
+ )
43
+ );
44
+ }
45
+ }
46
+
47
+ $ this ->documents = $ documents ;
48
+ }
49
+
50
+ /**
51
+ * @inheritdoc
52
+ */
53
+ public function writeToBulk (BulkWrite $ bulk )
54
+ {
55
+ foreach ($ this ->documents as $ document ) {
56
+ $ bulk ->insert ($ document );
57
+ }
58
+ }
59
+ }
You can’t perform that action at this time.
0 commit comments