TenantAwareSubscriber   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 1
cbo 3
dl 0
loc 40
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getSubscribedEvents() 0 6 1
A prePersist() 0 16 4
1
<?php
2
3
4
namespace Tahoe\Bundle\MultiTenancyBundle\EventSubscriber;
5
6
7
use Doctrine\Common\EventArgs;
8
use Doctrine\Common\EventSubscriber;
9
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
10
use Doctrine\ORM\Events;
11
use Symfony\Component\DependencyInjection\Container;
12
13
use Tahoe\Bundle\MultiTenancyBundle\Model\TenantAwareInterface;
14
use Tahoe\Bundle\MultiTenancyBundle\Service\TenantResolver;
15
16
class TenantAwareSubscriber implements EventSubscriber
17
{
18
    /**
19
     * @var TenantResolver
20
     */
21
    protected $tenantResolver;
22
    /**
23
     * @var Container
24
     */
25
    protected $container;
26
27
    public function __construct($container)
28
    {
29
        $this->container = $container;
30
    }
31
32
    public function getSubscribedEvents()
33
    {
34
        return array(
35
            Events::prePersist
36
        );
37
    }
38
39
    public function prePersist(LifecycleEventArgs $args)
40
    {
41
        /** @var TenantAwareInterface $object */
42
        $object = $args->getObject();
43
44
        // lazy loading to solve circular reference exception
45
        if ($this->tenantResolver == null) {
46
            $this->tenantResolver = $this->container->get('tahoe.multi_tenancy.tenant_resolver');
47
        }
48
49
        if ($object instanceof TenantAwareInterface) {
50
            if ($object->getTenant() === null) {
51
                $object->setTenant($this->tenantResolver->getTenant());
52
            }
53
        }
54
    }
55
}