Passed
Pull Request — master (#102)
by Damien
02:36
created

AuditSubscriber::onAuditEvent()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 37
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 26
nc 2
nop 1
dl 0
loc 37
rs 9.504
c 0
b 0
f 0
1
<?php
2
3
namespace DH\DoctrineAuditBundle\Event;
4
5
use DH\DoctrineAuditBundle\Manager\AuditManager;
6
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
7
8
class AuditSubscriber implements EventSubscriberInterface
9
{
10
    /**
11
     * @var AuditManager
12
     */
13
    private $manager;
14
15
    public function __construct(AuditManager $manager)
16
    {
17
        $this->manager = $manager;
18
    }
19
20
    public static function getSubscribedEvents()
21
    {
22
        return [
23
            AuditEvent::class => 'onAuditEvent',
24
        ];
25
    }
26
27
    /**
28
     * @param AuditEvent $event
29
     * @return AuditEvent
30
     * @throws \Doctrine\DBAL\DBALException
31
     */
32
    public function onAuditEvent(AuditEvent $event): AuditEvent
33
    {
34
        $payload = $event->getPayload();
35
        $auditTable = $payload['table'];
36
        unset($payload['table']);
37
38
        $fields = [
39
            'type' => ':type',
40
            'object_id' => ':object_id',
41
            'discriminator' => ':discriminator',
42
            'transaction_hash' => ':transaction_hash',
43
            'diffs' => ':diffs',
44
            'blame_id' => ':blame_id',
45
            'blame_user' => ':blame_user',
46
            'blame_user_fqdn' => ':blame_user_fqdn',
47
            'blame_user_firewall' => ':blame_user_firewall',
48
            'ip' => ':ip',
49
            'created_at' => ':created_at',
50
        ];
51
52
        $query = sprintf(
53
            'INSERT INTO %s (%s) VALUES (%s)',
54
            $auditTable,
55
            implode(', ', array_keys($fields)),
56
            implode(', ', array_values($fields))
57
        );
58
59
        $storage = $this->manager->selectStorageSpace($this->manager->getConfiguration()->getEntityManager());
60
        $statement = $storage->getConnection()->prepare($query);
61
62
        foreach ($payload as $key => $value) {
63
            $statement->bindValue($key, $value);
64
        }
65
66
        $statement->execute();
67
68
        return $event;
69
    }
70
}
71