Completed
Push — master ( 530ce9...1b2ae5 )
by Paweł
23:42 queued 20:31
created

TenantSubscriber   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 7
c 2
b 0
f 0
lcom 1
cbo 3
dl 0
loc 60
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getSubscribedEvents() 0 6 1
A prePersist() 0 4 1
A addTenant() 0 16 4
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
namespace SWP\Bundle\MultiTenancyBundle\EventListener;
15
16
use Doctrine\ORM\Events;
17
use Doctrine\ORM\Event\LifecycleEventArgs;
18
use Doctrine\Common\EventSubscriber;
19
use SWP\Component\MultiTenancy\Model\TenantAwareInterface;
20
use SWP\Component\MultiTenancy\Context\TenantContextInterface;
21
use Symfony\Component\DependencyInjection\ContainerInterface;
22
23
/**
24
 * Doctrine listener used to set tenant before the persist.
25
 */
26
class TenantSubscriber implements EventSubscriber
27
{
28
    /**
29
     * @var ContainerInterface
30
     */
31
    protected $container;
32
33
    /**
34
     * @var TenantContextInterface
35
     */
36
    protected $tenantContext;
37
38
    /**
39
     * Constructor.
40
     *
41
     * @param ContainerInterface $container
42
     */
43
    public function __construct(ContainerInterface $container)
44
    {
45
        $this->container = $container;
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function getSubscribedEvents()
52
    {
53
        return array(
54
            Events::prePersist,
55
        );
56
    }
57
58
    /**
59
     * @param LifecycleEventArgs $args
60
     */
61
    public function prePersist(LifecycleEventArgs $args)
62
    {
63
        $this->addTenant($args);
64
    }
65
66
    /**
67
     * @param LifecycleEventArgs $args
68
     */
69
    protected function addTenant(LifecycleEventArgs $args)
70
    {
71
        $entity = $args->getEntity();
72
        if ($entity instanceof TenantAwareInterface) {
73
            // skip when tenant is already set
74
            if (null !== $entity->getTenant()) {
75
                return;
76
            }
77
78
            if (null === $this->tenantContext) {
79
                $this->tenantContext = $this->container->get('swp_multi_tenancy.tenant_context');
80
            }
81
82
            $entity->setTenant($this->tenantContext->getTenant());
83
        }
84
    }
85
}
86