Completed
Pull Request — master (#49)
by Thomas
21:49
created

BulkInsert::finish()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
namespace ORM;
4
5
use ORM\Dbal\Dbal;
6
use ORM\Exception\InvalidArgument;
7
8
class BulkInsert
9
{
10
    /** @var string */
11
    protected $class;
12
13
    /** @var Dbal */
14
    protected $dbal;
15
16
    /** @var int */
17
    protected $limit;
18
19
    /** @var callable */
20
    protected $onSync;
21
22
    /** @var bool */
23
    protected $useAutoIncrement;
24
25
    /** @var Entity[] */
26
    protected $new = [];
27
28
    /** @var Entity[] */
29
    protected $synced = [];
30
31
    /**
32
     * BulkInsert constructor.
33
     *
34
     * @param string $class
35
     * @param Dbal $dbal
36
     * @param int $limit
37
     * @param callable $onSync
38
     * @param bool $useAutoIncrement
39
     */
40 13
    public function __construct(Dbal $dbal, $class, $useAutoIncrement = true, $limit = 20, callable $onSync = null)
41
    {
42 13
        $this->class = $class;
43 13
        $this->dbal = $dbal;
44 13
        $this->limit = $limit;
45 13
        $this->onSync = $onSync;
46 13
        $this->useAutoIncrement = $useAutoIncrement;
47 13
    }
48
49
    /**
50
     * Add an entity to the bulk insert.
51
     *
52
     * @param Entity ...$entities
53
     * @throws InvalidArgument
54
     */
55 6
    public function add(Entity ...$entities)
56
    {
57 6
        foreach ($entities as $entity) {
58 6
            if (!$entity instanceof $this->class) {
59 6
                throw new InvalidArgument('Only entities from type ' . $this->class . ' can be added');
60
            }
61
        }
62
63 5
        array_push($this->new, ...$entities);
64 5
        while (count($this->new) >= $this->limit) {
65 4
            $this->execute();
66
        }
67 5
    }
68
69
    /**
70
     * Insert the outstanding entities and return all synced objects.
71
     *
72
     * @return Entity[]
73
     */
74 3
    public function finish()
75
    {
76 3
        if (!empty($this->new)) {
77 1
            $this->execute();
78
        }
79 3
        return $this->synced;
80
    }
81
82
    /**
83
     * Executes the bulk insert.
84
     */
85 5
    protected function execute()
86
    {
87 5
        $new = array_splice($this->new, 0, $this->limit);
88 5
        if ($this->dbal->bulkInsert($new, $this->useAutoIncrement)) {
89 5
            array_push($this->synced, ...$new);
90 5
            !$this->onSync || call_user_func($this->onSync, $new);
91
        }
92 5
    }
93
}
94