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
|
|
|
* @param ContainerInterface $container |
38
|
|
|
*/ |
39
|
|
|
public function __construct(ContainerInterface $container) |
40
|
|
|
{ |
41
|
|
|
$this->container = $container; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* {@inheritdoc} |
46
|
|
|
*/ |
47
|
|
|
public function getSubscribedEvents() |
48
|
|
|
{ |
49
|
|
|
return [ |
50
|
|
|
Events::prePersist, |
51
|
|
|
Events::preUpdate, |
52
|
|
|
]; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param LifecycleEventArgs $args |
57
|
|
|
*/ |
58
|
|
|
public function prePersist(LifecycleEventArgs $args) |
59
|
|
|
{ |
60
|
|
|
$this->addTenant($args); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param PreUpdateEventArgs $args |
65
|
|
|
*/ |
66
|
|
|
public function preUpdate(PreUpdateEventArgs $args) |
67
|
|
|
{ |
68
|
|
|
$this->addTenant($args); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* @param LifecycleEventArgs $args |
73
|
|
|
*/ |
74
|
|
|
protected function addTenant(LifecycleEventArgs $args) |
75
|
|
|
{ |
76
|
|
|
$entity = $args->getEntity(); |
77
|
|
|
|
78
|
|
|
if ($entity instanceof TenantAwareInterface) { |
79
|
|
|
// skip when tenant is already set |
80
|
|
|
if (null !== $entity->getTenantCode()) { |
81
|
|
|
return; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
$tenantContext = $this->container->get('swp_multi_tenancy.tenant_context'); |
85
|
|
|
$entity->setTenantCode($tenantContext->getTenant()->getCode()); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|