DoctrineBatchHelper::wrapIterable()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 20
ccs 12
cts 12
cp 1
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shlinkio\Shlink\Core\Util;
6
7
use Doctrine\ORM\EntityManagerInterface;
8
use Throwable;
9
10
/**
11
 * Inspired by ocramius/doctrine-batch-utils https://github.com/Ocramius/DoctrineBatchUtils
12
 */
13
class DoctrineBatchHelper implements DoctrineBatchHelperInterface
14
{
15
    private EntityManagerInterface $em;
16
17 4
    public function __construct(EntityManagerInterface $em)
18
    {
19 4
        $this->em = $em;
20 4
    }
21
22
    /**
23
     * @throws Throwable
24
     */
25 4
    public function wrapIterable(iterable $resultSet, int $batchSize): iterable
26
    {
27 4
        $iteration = 0;
28
29 4
        $this->em->beginTransaction();
30
31
        try {
32 4
            foreach ($resultSet as $key => $value) {
33 3
                $iteration++;
34 3
                yield $key => $value;
35 3
                $this->flushAndClearBatch($iteration, $batchSize);
36
            }
37 1
        } catch (Throwable $e) {
38 1
            $this->em->rollback();
39
40 1
            throw $e;
41
        }
42
43 3
        $this->flushAndClearEntityManager();
44 3
        $this->em->commit();
45 3
    }
46
47 3
    private function flushAndClearBatch(int $iteration, int $batchSize): void
48
    {
49 3
        if ($iteration % $batchSize) {
50 2
            return;
51
        }
52
53 2
        $this->flushAndClearEntityManager();
54 1
    }
55
56 4
    private function flushAndClearEntityManager(): void
57
    {
58 4
        $this->em->flush();
59 3
        $this->em->clear();
60 3
    }
61
}
62