|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/* |
|
6
|
|
|
* This file is part of the Superdesk Web Publisher Core Bundle. |
|
7
|
|
|
* |
|
8
|
|
|
* Copyright 2017 Sourcefabric z.u. and contributors. |
|
9
|
|
|
* |
|
10
|
|
|
* For the full copyright and license information, please see the |
|
11
|
|
|
* AUTHORS and LICENSE files distributed with this source code. |
|
12
|
|
|
* |
|
13
|
|
|
* @copyright 2017 Sourcefabric z.ú |
|
14
|
|
|
* @license http://www.superdesk.org/license |
|
15
|
|
|
*/ |
|
16
|
|
|
|
|
17
|
|
|
namespace SWP\Bundle\CoreBundle\Context; |
|
18
|
|
|
|
|
19
|
|
|
use function array_key_exists; |
|
20
|
|
|
use SWP\Bundle\MultiTenancyBundle\Context\TenantContext; |
|
21
|
|
|
use SWP\Bundle\MultiTenancyBundle\MultiTenancyEvents; |
|
22
|
|
|
use SWP\Component\MultiTenancy\Exception\TenantNotFoundException; |
|
23
|
|
|
use SWP\Component\MultiTenancy\Model\TenantInterface; |
|
24
|
|
|
|
|
25
|
|
|
class CachedTenantContext extends TenantContext implements CachedTenantContextInterface |
|
26
|
|
|
{ |
|
27
|
|
|
private $resolvedTenants = []; |
|
28
|
|
|
|
|
29
|
|
|
public function getTenant(): ?TenantInterface |
|
30
|
|
|
{ |
|
31
|
|
|
$currentRequest = $this->requestStack->getCurrentRequest(); |
|
32
|
|
|
if ($currentRequest && $this->requestStack->getCurrentRequest()->attributes->get('exception') instanceof TenantNotFoundException) { |
|
33
|
|
|
return null; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
if (null === $this->tenant && null !== $currentRequest) { |
|
37
|
|
|
$cacheKey = self::getCacheKey($currentRequest->getHost()); |
|
38
|
|
|
if (!array_key_exists($cacheKey, $this->resolvedTenants) || $this->resolvedTenants[$cacheKey] instanceof TenantInterface) { |
|
39
|
|
|
$this->resolvedTenants[$cacheKey] = parent::getTenant(); |
|
40
|
|
|
} else { |
|
41
|
|
|
$this->tenant = $this->resolvedTenants[$cacheKey]; |
|
42
|
|
|
} |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
return $this->tenant; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
public function setTenant(TenantInterface $tenant): void |
|
49
|
|
|
{ |
|
50
|
|
|
parent::setTenant($tenant); |
|
51
|
|
|
$this->dispatcher->dispatch(MultiTenancyEvents::TENANTABLE_ENABLE); |
|
52
|
|
|
|
|
53
|
|
|
$host = $tenant->getSubdomain() ? $tenant->getSubdomain().'.'.$tenant->getDomainName() : $tenant->getDomainName(); |
|
54
|
|
|
$this->resolvedTenants[self::getCacheKey($host)] = $tenant; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
public function reset(): void |
|
58
|
|
|
{ |
|
59
|
|
|
$this->tenant = null; |
|
60
|
|
|
$this->resolvedTenants = []; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
private static function getCacheKey(string $host): string |
|
64
|
|
|
{ |
|
65
|
|
|
return md5('tenant_cache__'.$host); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|