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

TicketStatusListener::onFlush()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 11
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 20
rs 9.2
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