Completed
Push — develop ( 0686ac...7ecc3a )
by Alejandro
18s queued 11s
created

DoctrineBatchHelper   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 7
eloc 20
c 0
b 0
f 0
dl 0
loc 47
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A wrapIterable() 0 20 3
A flushAndClearEntityManager() 0 4 1
A flushAndClearBatch() 0 7 2
A __construct() 0 3 1
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
    public function __construct(EntityManagerInterface $em)
18
    {
19
        $this->em = $em;
20
    }
21
22
    /**
23
     * @throws Throwable
24
     */
25
    public function wrapIterable(iterable $resultSet, int $batchSize): iterable
26
    {
27
        $iteration = 0;
28
29
        $this->em->beginTransaction();
30
31
        try {
32
            foreach ($resultSet as $key => $value) {
33
                $iteration++;
34
                yield $key => $value;
35
                $this->flushAndClearBatch($iteration, $batchSize);
36
            }
37
        } catch (Throwable $e) {
38
            $this->em->rollback();
39
40
            throw $e;
41
        }
42
43
        $this->flushAndClearEntityManager();
44
        $this->em->commit();
45
    }
46
47
    private function flushAndClearBatch(int $iteration, int $batchSize): void
48
    {
49
        if ($iteration % $batchSize) {
50
            return;
51
        }
52
53
        $this->flushAndClearEntityManager();
54
    }
55
56
    private function flushAndClearEntityManager(): void
57
    {
58
        $this->em->flush();
59
        $this->em->clear();
60
    }
61
}
62