Completed
Pull Request — master (#1)
by Rafał
12:20 queued 05:49
created

TenantResolver::resolve()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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