Skip to content

Commit 86eef25

Browse files
author
Petr Buchyn
committed
InsertMany write model and it's usage in Collection::insertMany()
1 parent b609491 commit 86eef25

File tree

2 files changed

+62
-7
lines changed

2 files changed

+62
-7
lines changed

src/Collection.php

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use Tequila\MongoDB\Traits\ResolveReadWriteOptionsTrait;
1919
use Tequila\MongoDB\Write\Model\DeleteMany;
2020
use Tequila\MongoDB\Write\Model\DeleteOne;
21+
use Tequila\MongoDB\Write\Model\InsertMany;
2122
use Tequila\MongoDB\Write\Model\InsertOne;
2223
use Tequila\MongoDB\Write\Model\ReplaceOne;
2324
use Tequila\MongoDB\Write\Model\UpdateMany;
@@ -427,13 +428,8 @@ public function getNamespace()
427428
*/
428429
public function insertMany($documents, array $options = [])
429430
{
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);
437433

438434
return new InsertManyResult($bulkWriteResult);
439435
}

src/Write/Model/InsertMany.php

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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+
}

0 commit comments

Comments
 (0)