Completed
Push — master ( a78262...4e959e )
by Roni
11:36
created

Logger::saveLog()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of the XiideaEasyAuditBundle package.
5
 *
6
 * (c) Xiidea <http://www.xiidea.net>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Xiidea\EasyAuditBundle\Logger;
13
14
use Doctrine\ORM\EntityManager;
15
use Xiidea\EasyAuditBundle\Entity\BaseAuditLog as AuditLog;
16
use Doctrine\Bundle\DoctrineBundle\Registry;
17
use Xiidea\EasyAuditBundle\Events\DoctrineEvents;
18
19
class Logger implements LoggerInterface
20
{
21
    private $entityDeleteLogs = [];
22
23
    /**
24
     * @var \Doctrine\Bundle\DoctrineBundle\Registry
25
     */
26
    private $doctrine;
27
28
    public function __construct(Registry $doctrine)
29
    {
30
        $this->doctrine = $doctrine;
31
    }
32
33
    public function log(AuditLog $event = null)
34
    {
35
        if(empty($event)) {
36
            return;
37
        }
38
39
        if($event->getTypeId() === DoctrineEvents::ENTITY_DELETED) {
40
            $this->entityDeleteLogs[] = $event;
41
            return;
42
        }
43
44
        $this->saveLog($event);
45
    }
46
47
    /**
48
     * @return EntityManager
49
     */
50
    protected function getEntityManager()
51
    {
52
         return $this->getDoctrine()->getManager();
53
    }
54
55
    /**
56
     * @return \Doctrine\Bundle\DoctrineBundle\Registry
57
     */
58
    public function getDoctrine()
59
    {
60
        return $this->doctrine;
61
    }
62
63
    /**
64
     * @param AuditLog $event
65
     * @throws \Doctrine\ORM\ORMException
66
     * @throws \Doctrine\ORM\OptimisticLockException
67
     */
68
    protected function saveLog(AuditLog $event)
69
    {
70
        $this->getEntityManager()->persist($event);
71
        $this->getEntityManager()->flush($event);
72
    }
73
74
    public function savePendingLogs()
75
    {
76
        foreach ($this->entityDeleteLogs as $log) {
77
            $this->saveLog($log);
78
        }
79
80
        $this->entityDeleteLogs = [];
81
    }
82
83
}
84