HostnameLocator::getTenantFromRequest()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Vivait\TenantBundle\Locator;
4
5
use Symfony\Component\HttpFoundation\Request;
6
7
/**
8
 * @see HostnameLocatorSpec
9
 */
10
class HostnameLocator implements TenantLocator
11
{
12
    private $pattern = '#^(?P<tenant>.+?)\.(.*?)\.#';
13
    private $request;
14
15
    public function __construct( Request $request )
0 ignored issues
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
16
    {
17
        $this->request = $request;
18
    }
19
20
    /**
21
     * @return string Tenant key
22
     */
23
    public function getTenant() {
24
        // Get the server name
25
        $host = $this->request->getHost();
26
27
        if (!preg_match( $this->pattern, $host, $matches )) {
28
            throw new \RuntimeException(sprintf('Could not match tenant for host "%s"', $host));
29
        }
30
31
        return $matches['tenant'];
32
    }
33
34
    /**
35
     * Gets the REGEX pattern used to match a tenant
36
     * @return string
37
     */
38
    public function getPattern()
39
    {
40
        return $this->pattern;
41
    }
42
43
    /**
44
     * Sets the REGEX pattern used to match a tenant
45
     * @param string $pattern
46
     * @return $this
47
     */
48
    public function setPattern( $pattern )
49
    {
50
        $this->pattern = $pattern;
51
52
        return $this;
53
    }
54
55
    /**
56
     * @param Request $request
57
     * @return string Tenant key
58
     */
59
    public static function getTenantFromRequest(Request $request) {
60
        $locator = new self($request);
61
        return $locator->getTenant();
62
    }
63
}
64