Completed
Pull Request — master (#1)
by Rafał
02:38
created

TenantableListener   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
c 1
b 0
f 0
lcom 1
cbo 4
dl 0
loc 49
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A onKernelRequest() 0 11 2
A getSubscribedEvents() 0 6 1
1
<?php
2
3
/**
4
 * This file is part of the Superdesk Web Publisher MultiTenancy Bundle.
5
 *
6
 * Copyright 2016 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 2016 Sourcefabric z.ú.
12
 * @license http://www.superdesk.org/license
13
 */
14
namespace SWP\MultiTenancyBundle\EventListener;
15
16
use Doctrine\ORM\EntityManagerInterface;
17
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
18
use Symfony\Component\HttpKernel\KernelEvents;
19
use SWP\Component\MultiTenancy\Context\TenantContextInterface;
20
21
/**
22
 * TenantableListener class.
23
 *
24
 * It makes sure all SELECT queries are tenant aware.
25
 */
26
class TenantableListener implements EventSubscriberInterface
27
{
28
    /**
29
     * @var TenantContextInterface
30
     */
31
    protected $tenantContext;
32
33
    /**
34
     * @var EntityManagerInterface
35
     */
36
    protected $entityManager;
37
38
    /**
39
     * Construct.
40
     *
41
     * @param EntityManagerInterface $entityManager
42
     * @param TenantContextInterface $tenantContext
43
     */
44
    public function __construct(EntityManagerInterface $entityManager, TenantContextInterface $tenantContext)
45
    {
46
        $this->entityManager = $entityManager;
47
        $this->tenantContext = $tenantContext;
48
    }
49
50
    /**
51
     * Enables tenantable filter on kernel.request.
52
     */
53
    public function onKernelRequest()
54
    {
55
        $tenant = $this->tenantContext->getTenant();
56
        $tenantId = $tenant->getId();
57
        if ($tenantId) {
58
            $this->entityManager
59
                ->getFilters()
60
                ->enable('tenantable')
61
                ->setParameter('tenantId', $tenantId);
62
        }
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public static function getSubscribedEvents()
69
    {
70
        return [
71
            KernelEvents::REQUEST => 'onKernelRequest',
72
        ];
73
    }
74
}
75