ORMBatchProcessor   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Test Coverage

Coverage 86.67%

Importance

Changes 0
Metric Value
eloc 28
dl 0
loc 55
rs 10
c 0
b 0
f 0
ccs 26
cts 30
cp 0.8667
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A flushAndClearBatch() 0 7 2
A getIterator() 0 23 3
A flushAndClear() 0 4 1
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