FlushSubscriber   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
c 1
b 0
f 0
lcom 1
cbo 2
dl 0
loc 32
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getSubscribedEvents() 0 4 1
A preFlush() 0 21 4
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