1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Vivait\TenantBundle\Locator; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\HttpFoundation\Request; |
6
|
|
|
use Vivait\TenantBundle\Registry\TenantRegistry; |
7
|
|
|
|
8
|
|
|
class CookieLocator implements TenantLocator |
9
|
|
|
{ |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @var Request |
13
|
|
|
*/ |
14
|
|
|
private $request; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var string |
18
|
|
|
*/ |
19
|
|
|
private $cookieName; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var TenantRegistry |
23
|
|
|
*/ |
24
|
|
|
private $tenantRegistry; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param Request $request |
28
|
|
|
* @param $cookieName |
29
|
|
|
* @param TenantRegistry $tenantRegistry |
30
|
|
|
*/ |
31
|
|
|
public function __construct(Request $request, $cookieName, TenantRegistry $tenantRegistry) |
|
|
|
|
32
|
|
|
{ |
33
|
|
|
$this->request = $request; |
34
|
|
|
$this->cookieName = $cookieName; |
35
|
|
|
$this->tenantRegistry = $tenantRegistry; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @return string |
40
|
|
|
*/ |
41
|
|
|
public function getTenant() |
42
|
|
|
{ |
43
|
|
|
$tenantName = $this->request->cookies->get($this->cookieName); |
44
|
|
|
|
45
|
|
|
$this->checkTenantName($tenantName); |
46
|
|
|
|
47
|
|
|
return $tenantName; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param Request $request |
52
|
|
|
* @param string $cookieName |
53
|
|
|
* @param TenantRegistry $tenantRegistry |
54
|
|
|
* |
55
|
|
|
* @return string Tenant key |
56
|
|
|
*/ |
57
|
|
|
public static function getTenantFromRequest( |
58
|
|
|
Request $request, |
59
|
|
|
$cookieName = 'tenant', |
60
|
|
|
TenantRegistry $tenantRegistry |
61
|
|
|
) { |
62
|
|
|
$locator = new self($request, $cookieName, $tenantRegistry); |
63
|
|
|
|
64
|
|
|
return $locator->getTenant(); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @param $tenantName |
69
|
|
|
* |
70
|
|
|
* @return bool |
71
|
|
|
*/ |
72
|
|
|
private function tenantNameIsValid($tenantName) |
73
|
|
|
{ |
74
|
|
|
return $this->tenantRegistry->contains($tenantName) && $tenantName !== 'dev' && $tenantName !== 'test'; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @throws \RuntimeException |
79
|
|
|
* @throws \OutOfBoundsException |
80
|
|
|
* |
81
|
|
|
* @param $tenantName |
82
|
|
|
*/ |
83
|
|
|
private function checkTenantName($tenantName) |
84
|
|
|
{ |
85
|
|
|
// if no cookie, throw runtime so it'll continue as prod |
86
|
|
|
if ($tenantName === null) { |
87
|
|
|
throw new \RuntimeException; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
// if tenant is set and doesn't exist, throw out of bounds |
91
|
|
|
if ( ! $this->tenantNameIsValid($tenantName)) { |
92
|
|
|
throw new \OutOfBoundsException; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|