TenantSubscriber   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 0
Metric Value
wmc 9
lcom 0
cbo 4
dl 0
loc 55
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getSubscribedEvents() 0 7 1
A prePersist() 0 4 1
A preUpdate() 0 8 3
A addTenant() 0 14 3
1
<?php
2
3
/*
4
 * This file is part of the Superdesk Web Publisher MultiTenancy Bundle.
5
 *
6
 * Copyright 2015 Sourcefabric z.u. and contributors.
7
 *
8
 * For the full copyright and license information, please see the
9
 * AUTHORS and LICENSE files distributed with this source code.
10
 *
11
 * @copyright 2015 Sourcefabric z.ú
12
 * @license http://www.superdesk.org/license
13
 */
14
15
namespace SWP\Bundle\MultiTenancyBundle\EventListener;
16
17
use Doctrine\Common\EventSubscriber;
18
use Doctrine\ORM\Event\LifecycleEventArgs;
19
use Doctrine\ORM\Event\PreUpdateEventArgs;
20
use Doctrine\ORM\Events;
21
use SWP\Component\MultiTenancy\Model\TenantAwareInterface;
22
use Symfony\Component\DependencyInjection\ContainerInterface;
23
24
/**
25
 * Doctrine listener used to set tenant before the persist.
26
 */
27
final class TenantSubscriber implements EventSubscriber
28
{
29
    /**
30
     * @var ContainerInterface
31
     */
32
    protected $container;
33
34
    /**
35
     * Constructor.
36
     */
37
    public function __construct(ContainerInterface $container)
38
    {
39
        $this->container = $container;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function getSubscribedEvents()
46
    {
47
        return [
48
            Events::prePersist,
49
            Events::preUpdate,
50
        ];
51
    }
52
53
    public function prePersist(LifecycleEventArgs $args)
54
    {
55
        $this->addTenant($args);
56
    }
57
58
    public function preUpdate(PreUpdateEventArgs $args)
59
    {
60
        $entity = $args->getEntity();
61
62
        if (($entity instanceof TenantAwareInterface) && null === $entity->getTenantCode()) {
63
            return;
64
        }
65
    }
66
67
    protected function addTenant(LifecycleEventArgs $args)
68
    {
69
        $entity = $args->getEntity();
70
71
        if ($entity instanceof TenantAwareInterface) {
72
            // skip when tenant is already set
73
            if (null !== $entity->getTenantCode()) {
74
                return;
75
            }
76
77
            $tenantContext = $this->container->get('swp_multi_tenancy.tenant_context');
78
            $entity->setTenantCode($tenantContext->getTenant()->getCode());
79
        }
80
    }
81
}
82