Failed Conditions
Pull Request — 0.3 (#20)
by jean
12:27
created

DoctrinePersister   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 55
ccs 29
cts 29
cp 1
rs 10
c 0
b 0
f 0
wmc 11

5 Methods

Rating   Name   Duplication   Size   Complexity  
A persist() 0 14 2
A finalize() 0 3 1
A clear() 0 13 6
A writeBatch() 0 6 1
A __construct() 0 3 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: darkilliant
5
 * Date: 5/8/18
6
 * Time: 7:56 AM.
7
 */
8
9
namespace Darkilliant\ImportBundle\Persister;
10
11
use Doctrine\ORM\EntityManagerInterface;
12
13
/**
14
 * @internal
15
 */
16
class DoctrinePersister implements PersisterInterface
17
{
18
    private $em;
19
    private $batch = 0;
20
21
    private $whiteList = [];
22
    private $blackList = [];
23
24 5
    public function __construct(EntityManagerInterface $em)
25
    {
26 5
        $this->em = $em;
27 5
    }
28
29 5
    public function persist($entity, $batchCount = 20, $whiteList = [], $blackList = [])
30
    {
31 5
        ++$this->batch;
32 5
        $this->whiteList = $whiteList;
33 5
        $this->blackList = $blackList;
34
35 5
        $this->em->persist($entity);
36
37 5
        if ($this->batch >= $batchCount) {
38 1
            $this->writeBatch();
39
            return true;
40 5
        }
41
42 3
        return false;
43
    }
44 3
45 2
    public function finalize()
46
    {
47 4
        $this->writeBatch();
48
    }
49 4
50 4
    private function writeBatch()
51
    {
52 3
        $this->em->flush();
53 3
        $this->clear();
54
55 4
        $this->batch = 0;
56
    }
57 4
58 2
    private function clear()
59 2
    {
60 1
        if (empty($this->whiteList) && empty($this->blackList)) {
61 1
            $this->em->clear();
62
        } elseif (!empty($this->whiteList)) {
63 1
            foreach ($this->whiteList as $class) {
64 1
                $this->em->clear($class);
65
            }
66
        } elseif (!empty($this->blackList)) {
67 3
            throw new \Exception('unsupported blacklist');
68 3
        }
69
70
        gc_collect_cycles();
71
    }
72
}
73