Completed
Pull Request — master (#147)
by Serhii
14:54
created

TicketStatusListener   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 43
rs 10
wmc 9
lcom 0
cbo 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A onFlush() 0 20 4
B checkTicketStatusUpdate() 0 13 5
1
<?php
2
3
namespace AppBundle\EventListener;
4
5
use AppBundle\Entity\Ticket;
6
use AppBundle\Exception\TicketStatusConflictException;
7
use Doctrine\ORM\Event\OnFlushEventArgs;
8
use Doctrine\ORM\UnitOfWork;
9
10
class TicketStatusListener
11
{
12
    public function onFlush(OnFlushEventArgs $args)
13
    {
14
        $em = $args->getEntityManager();
15
        $uow = $em->getUnitOfWork();
16
17
        if (!$ticket = $this->checkTicketStatusUpdate($uow)) {
18
            return;
19
        }
20
21
        $oldStatus = $uow->getEntityChangeSet($ticket)['status'][0];
22
        $newStatus = $uow->getEntityChangeSet($ticket)['status'][1];
23
24
        if (!in_array($newStatus, Ticket::getStatuses())) {
25
            throw new \InvalidArgumentException("Invalid ticket status");
26
        }
27
28
        if ($oldStatus === Ticket::STATUS_PAID) {
29
            throw new TicketStatusConflictException("Invalid status. Ticket already paid.");
30
        }
31
    }
32
33
    /**
34
     * Checks if ticket status was updated
35
     *
36
     * @param UnitOfWork $uow
37
     * @return Ticket|false
38
     */
39
    private function checkTicketStatusUpdate(UnitOfWork $uow)
40
    {
41
        if (!$uow->getScheduledEntityUpdates()) {
42
            return false;
43
        }
44
45
        foreach ($uow->getScheduledEntityUpdates() as $entity) {
46
            if (!$entity instanceof Ticket && !key_exists('status', $uow->getEntityChangeSet($entity))) {
47
                return false;
48
            }
49
            return $entity;
50
        }
51
    }
52
}
53