Completed
Push — master ( 028caf...8f241c )
by Rafał
03:04
created

TenantResolver::assertTenantIsFound()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 2
eloc 3
nc 2
nop 2
1
<?php
2
3
/**
4
 * This file is part of the Superdesk Web Publisher MultiTenancy Component.
5
 *
6
 * Copyright 2015 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 2015 Sourcefabric z.ú
12
 * @license http://www.superdesk.org/license
13
 */
14
15
namespace SWP\Component\MultiTenancy\Resolver;
16
17
use SWP\Component\MultiTenancy\Exception\TenantNotFoundException;
18
use SWP\Component\MultiTenancy\Repository\TenantRepositoryInterface;
19
20
/**
21
 * TenantResolver resolves the tenant based on subdomain.
22
 */
23
class TenantResolver implements TenantResolverInterface
24
{
25
    /**
26
     * @var string
27
     */
28
    private $domain;
29
30
    /**
31
     * @var TenantRepositoryInterface
32
     */
33
    private $tenantRepository;
34
35
    /**
36
     * Construct.
37
     *
38
     * @param string                    $domain
39
     * @param TenantRepositoryInterface $tenantRepository
40
     */
41
    public function __construct($domain, TenantRepositoryInterface $tenantRepository)
42
    {
43
        $this->domain = $domain;
44
        $this->tenantRepository = $tenantRepository;
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50
    public function resolve($host = null)
51
    {
52
        if (null === $host) {
53
            $host = self::DEFAULT_TENANT;
54
        }
55
56
        $subdomain = $this->extractSubdomain($host);
57
        $tenant = $this->tenantRepository->findOneBySubdomain($subdomain);
58
59
        if (null === $tenant) {
60
            throw new TenantNotFoundException($subdomain);
61
        }
62
63
        return $tenant;
64
    }
65
66
    /**
67
     * Extracts subdomain from the host.
68
     *
69
     * @param string $host Hostname
70
     *
71
     * @return string
72
     */
73
    protected function extractSubdomain($host)
74
    {
75
        if ($this->domain === $host) {
76
            return self::DEFAULT_TENANT;
77
        }
78
79
        $parts = explode('.', str_replace('.'.$this->domain, '', $host));
80
        $subdomain = self::DEFAULT_TENANT;
81
        if (count($parts) === 1 && $parts[0] !== 'www') {
82
            $subdomain = $parts[0];
83
        }
84
85
        return $subdomain;
86
    }
87
}
88