TenantResolver::resolveTenantFromUser()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 5
rs 9.4285
cc 3
eloc 3
nc 4
nop 0
1
<?php
2
3
4
namespace Tahoe\Bundle\MultiTenancyBundle\Service;
5
6
7
use Doctrine\ORM\EntityRepository;
8
use Symfony\Component\HttpFoundation\RequestStack;
9
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
10
use Tahoe\Bundle\MultiTenancyBundle\Entity\Tenant;
11
use Tahoe\Bundle\MultiTenancyBundle\Model\MultiTenantTenantInterface;
12
use Tahoe\Bundle\MultiTenancyBundle\Model\MultiTenantUserInterface;
13
14
class TenantResolver
15
{
16
    const STRATEGY_TENANT_AWARE_SUBDOMAIN = 'tenant_aware';
17
    const STRATEGY_FIXED_SUBDOMAIN = 'fixed';
18
19
    /**
20
     * @var RequestStack
21
     */
22
    protected $requestStack;
23
    /**
24
     * @var string
25
     */
26
    protected $domain;
27
28
    /**
29
     * @var EntityRepository
30
     */
31
    protected $tenantRepository;
32
33
    /**
34
     * @var MultiTenantTenantInterface
35
     */
36
    protected $tenant;
37
38
    protected $strategy;
39
40
    protected $token;
41
42
    public function __construct($requestStack, $domain, $tenantRepository, TokenStorage $token, $strategy)
43
    {
44
        $this->requestStack = $requestStack;
45
        $this->domain = $domain;
46
        $this->tenantRepository = $tenantRepository;
47
        $this->token = $token;
48
        $this->strategy = $strategy;
49
    }
50
51
52
    /**
53
     * Returns an tenant id based on current url
54
     *
55
     * @return int
56
     * @throws \Exception
57
     */
58
    public function getTenantId()
59
    {
60
        if ($this->tenant === null) {
61
            $this->tenant =  $this->resolveTenant();
62
        }
63
64
        return ($this->tenant) ? $this->tenant->getId() : null;
65
    }
66
67
68
    /**
69
     * Returns an tenant entity based on current url
70
     *
71
     * @return MultiTenantTenantInterface
72
     * @throws \Exception
73
     */
74
    public function getTenant()
75
    {
76
        if ($this->tenant === null) {
77
            $this->tenant =  $this->resolveTenant();
78
        }
79
80
        return  $this->tenant;
81
    }
82
83
    public function isSubdomain()
84
    {
85
        $host = $this->requestStack->getCurrentRequest()->getHost();
86
87
        $parts = explode('.', str_replace('.' . $this->domain, '', $host));
88
89
        $subdomain = null;
90
91 View Code Duplication
        if (count($parts) === 1 && $parts[0] !== 'www') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
92
            $subdomain = $parts[0];
93
        }
94
95
        return !empty($subdomain);
96
    }
97
98
    /**
99
     * @return MultiTenantTenantInterface
100
     * @throws \Exception
101
     */
102
    protected function resolveTenant()
103
    {
104
        // we check if tenant was setted by the override method
105
        if ($this->tenant) {
106
            return $this->tenant;
107
        }
108
        // we check which strategy was chosen to resolve the tenant
109
        if ($this->strategy == self::STRATEGY_TENANT_AWARE_SUBDOMAIN ) {
110
            return $this->resolveTenantFromSubdomain();
111
        } else if ($this->strategy == self::STRATEGY_FIXED_SUBDOMAIN) {
112
            return $this->resolveTenantFromUser();
113
        }
114
115
        // we don't know the strategy, we thrown an exception here
116
        throw new \Exception('Strategy unknown! Please provide the correct strategy.');
117
    }
118
119
    public function getStrategy()
120
    {
121
        return $this->strategy;
122
    }
123
124
    public function needStartScreen()
125
    {
126
        /** @var MultiTenantUserInterface $user */
127
        $user = $this->token->getToken()->getUser();
128
        return ($this->strategy == self::STRATEGY_FIXED_SUBDOMAIN and !$user->getActiveTenant())
129
            or ($this->strategy == self::STRATEGY_TENANT_AWARE_SUBDOMAIN and !$this->isSubdomain());
130
    }
131
132
    /**
133
     * @return Tenant
134
     */
135
    protected function resolveTenantFromUser()
136
    {
137
        $token = $this->token->getToken();
138
        return ($token && is_object($token->getUser())) ? $token->getUser()->getActiveTenant() : null;
139
    }
140
141
    /**
142
     * @return Tenant
143
     * @throws \Exception
144
     */
145
    protected function resolveTenantFromSubdomain()
146
    {
147
        $host = $this->requestStack->getCurrentRequest()->getHost();
148
149
        if ($host === $this->domain) {
150
            throw new \Exception('Tenant resolver cannot be used in root domain. it only works for sub domains');
151
        }
152
153
        $parts = explode('.', str_replace('.' . $this->domain, '', $host));
154
155
        $subdomain = null;
156
157 View Code Duplication
        if (count($parts) === 1 && $parts[0] !== 'www') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
158
            $subdomain = $parts[0];
159
        }
160
161
        $tenant = $this->tenantRepository->findOneBy(array('subdomain' => $subdomain));
162
163
        if ($tenant) {
164
            $this->tenant = $tenant;
165
166
            return $this->tenant;
167
        }
168
169
        throw new \Exception(sprintf('Tenant with sub domain %s doesn\'t exist', $subdomain));
170
    }
171
172
    /**

173
     * @param Tenant $tenant

0 ignored issues
show
Documentation introduced by
There is no parameter named $tenant
. Did you maybe mean $tenant?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
174
     *

175
     * @return $this

0 ignored issues
show
Documentation introduced by
The doc-type $this
 could not be parsed: Unknown type name "$this
" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
176
     */
177
    public function overrideTenant(Tenant $tenant)
178
    {
179
        $this->tenant = $tenant;
180
        return $this;
181
    }
182
}
183