FlushSubscriber::getSubscribedEvents()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace AppBundle\EventListener;
4
5
use Doctrine\Common\EventSubscriber;
6
use Doctrine\ORM\Events;
7
use Doctrine\ORM\Event\PreFlushEventArgs;
8
9
class FlushSubscriber implements EventSubscriber
10
{
11
    public $flushed;
12
    public $inRequest = false;
13
14
    public function preFlush(PreFlushEventArgs $args)
15
    {
16
        if (!$this->inRequest) {
17
            // let console commands handle flushes anyway they want
18
            return;
19
        }
20
21
        $em = $args->getEntityManager();
22
        if ($em->getConnection()->isTransactionActive()) {
23
            // the transaction is managed manually and was already started
24
            // probably it won't be handled since it is the end of response
25
            // but anyways, it won't cause trouble
26
            return;
27
        }
28
29
        if ($this->flushed) {
30
            throw new \BadMethodCallException("The flush can be run only once and is run automatically in the end of each request to prevent data inconsistencies and bad design.");
31
        }
32
33
        $this->flushed = true;
34
    }
35
36
    public function getSubscribedEvents()
37
    {
38
        return [Events::preFlush];
39
    }
40
}
41