Passed
Branch main (b6a268)
by Iain
04:11
created

CurrentTenantProvider   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 41
rs 10
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getCurrentTenant() 0 22 5
A setTenant() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * Copyright Humbly Arrogant Ltd 2020-2022.
7
 *
8
 * Use of this software is governed by the Business Source License included in the LICENSE file and at https://getparthenon.com/docs/next/license.
9
 *
10
 * Change Date: TBD ( 3 years after 2.0.0 release )
11
 *
12
 * On the date above, in accordance with the Business Source License, use of this software will be governed by the open source license specified in the LICENSE file.
13
 */
14
15
namespace Parthenon\MultiTenancy\TenantProvider;
16
17
use Parthenon\Common\Exception\GeneralException;
18
use Parthenon\Common\Exception\NoEntityFoundException;
19
use Parthenon\MultiTenancy\Entity\Tenant;
20
use Parthenon\MultiTenancy\Entity\TenantInterface;
21
use Parthenon\MultiTenancy\Exception\NoTenantFoundException;
22
use Parthenon\MultiTenancy\Repository\TenantRepositoryInterface;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\HttpFoundation\RequestStack;
25
26
final class CurrentTenantProvider implements TenantProviderInterface
27
{
28
    private TenantInterface $tenant;
29
30
    public function __construct(
31
        private TenantRepositoryInterface $tenantRepository,
32
        private RequestStack $requestStack,
33
        private string $defaultDatabase,
34
    ) {
35
    }
36
37
    public function setTenant(TenantInterface $tenant): void
38
    {
39
        $this->tenant = $tenant;
40
    }
41
42
    /**
43
     * @throws GeneralException
44
     */
45
    public function getCurrentTenant(bool $refresh = false): TenantInterface
46
    {
47
        if (isset($this->tenant) && !$refresh) {
48
            return $this->tenant;
49
        }
50
51
        $request = $this->requestStack->getMainRequest();
52
53
        if (!$request instanceof Request) {
54
            return Tenant::createWithSubdomainAndDatabase($this->defaultDatabase, 'dummy.subdomain');
55
        }
56
57
        $host = $request->getHost();
58
        $subdomain = preg_replace('~^([a-z0-9-]+)(\..*)$~', '$1', $host);
59
60
        try {
61
            $this->tenant = $this->tenantRepository->findBySubdomain($subdomain);
62
        } catch (NoEntityFoundException $e) {
63
            throw new NoTenantFoundException(sprintf('Unable to find tenant for \'%s\'', $subdomain), $e->getCode(), $e);
64
        }
65
66
        return $this->tenant;
67
    }
68
}
69