Completed
Pull Request — master (#1)
by Rafał
03:27
created

TenantResolver::resolve()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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