ORMBatchProcessor::flushAndClearBatch()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
ccs 4
cts 4
cp 1
crap 2
1
<?php
2
3
namespace Zenstruck\Porpaginas\Doctrine\Batch;
4
5
use Doctrine\ORM\EntityManagerInterface;
6
use Doctrine\ORM\Internal\Hydration\IterableResult;
7
8
/**
9
 * @author Marco Pivetta <[email protected]>
10
 * @author Kevin Bond <[email protected]>
11
 */
12
final class ORMBatchProcessor implements \IteratorAggregate
13
{
14
    private iterable $items;
15
    private EntityManagerInterface $em;
16
    private int $chunkSize;
17
18 16
    public function __construct(iterable $items, EntityManagerInterface $em, int $chunkSize = 100)
19
    {
20 16
        if ($items instanceof IterableResult) {
21
            $items = new ORMIterableResultDecorator($items);
22
        }
23
24 16
        $this->items = $items;
25 16
        $this->em = $em;
26 16
        $this->chunkSize = $chunkSize;
27 16
    }
28
29 16
    public function getIterator(): \Traversable
30
    {
31 16
        $logger = $this->em->getConfiguration()->getSQLLogger();
32 16
        $this->em->getConfiguration()->setSQLLogger(null);
33 16
        $this->em->beginTransaction();
34
35 16
        $iteration = 0;
36
37
        try {
38 16
            foreach ($this->items as $key => $value) {
39 16
                yield $key => $value;
40
41 16
                $this->flushAndClearBatch(++$iteration);
42
            }
43
        } catch (\Throwable $exception) {
44
            $this->em->rollback();
45
46
            throw $exception;
47
        }
48
49 16
        $this->flushAndClear();
50 16
        $this->em->commit();
51 16
        $this->em->getConfiguration()->setSQLLogger($logger);
52 16
    }
53
54 16
    private function flushAndClearBatch(int $iteration): void
55
    {
56 16
        if ($iteration % $this->chunkSize) {
57 16
            return;
58
        }
59
60 7
        $this->flushAndClear();
61 7
    }
62
63 16
    private function flushAndClear(): void
64
    {
65 16
        $this->em->flush();
66 16
        $this->em->clear();
67 16
    }
68
}
69