Completed
Pull Request — master (#1)
by Rafał
03:36 queued 01:22
created

TenantSubscriber   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 51
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 51
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 12 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
namespace SWP\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
22
/**
23
 * Doctrine listener used to set tenant before the persist.
24
 */
25
class TenantSubscriber implements EventSubscriber
26
{
27
    /**
28
     * @var TenantContextInterface
29
     */
30
    protected $tenantContext;
31
32
    /**
33
     * Constructor.
34
     *
35
     * @param TenantContextInterface $tenantContext
36
     */
37
    public function __construct(TenantContextInterface $tenantContext)
38
    {
39
        $this->tenantContext = $tenantContext;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function getSubscribedEvents()
46
    {
47
        return array(
48
            Events::prePersist,
49
        );
50
    }
51
52
    /**
53
     * @param LifecycleEventArgs $args
54
     */
55
    public function prePersist(LifecycleEventArgs $args)
56
    {
57
        $this->addTenant($args);
58
    }
59
60
    /**
61
     * @param LifecycleEventArgs $args
62
     */
63
    protected function addTenant(LifecycleEventArgs $args)
64
    {
65
        $entity = $args->getEntity();
66
        if ($entity instanceof TenantAwareInterface) {
67
            // skip when tenant is already set
68
            if (null !== $entity->getTenant()) {
69
                return;
70
            }
71
72
            $entity->setTenant($this->tenantContext->getTenant());
73
        }
74
    }
75
}
76