Completed
Push — master ( dacc40...01610c )
by Vojtěch
8s
created

NetteRequestDetector::match()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.6737
c 0
b 0
f 0
cc 6
eloc 13
nc 10
nop 2
1
<?php
2
3
namespace SixtyEightPublishers\Application\Detector;
4
5
use Nette\Http\IRequest;
6
use Nette\Utils\Strings;
7
use SixtyEightPublishers\Application\IEnvironmentDetector;
8
use SixtyEightPublishers\Application\Profile;
9
use SixtyEightPublishers\Application\ProfileContainer;
10
11
12
class NetteRequestDetector implements IEnvironmentDetector
13
{
14
	/** @var \Nette\Http\IRequest  */
15
	private $request;
16
17
	/**
18
	 * @param \Nette\Http\IRequest $request
19
	 */
20
	public function __construct(IRequest $request)
21
	{
22
		$this->request = $request;
23
	}
24
25
	/**
26
	 * {@inheritdoc}
27
	 */
28
	public function detect(ProfileContainer $profileContainer)
29
	{
30
		$url = $this->request->getUrl()->getHost();
31
32
		/** @var Profile $profile */
33
		foreach ($profileContainer as $profile)
34
			foreach ($profile->getDomains() as $domain)
35
				if ((Strings::contains($domain, '*') && $this->match($domain, $url)) || ($domain === $url))
36
					return $profile;
37
38
		return null;
39
	}
40
41
	/**
42
	 * @param string    $domain
43
	 * @param string    $url
44
	 *
45
	 * @return bool
46
	 */
47
	private function match($domain, $url)
48
	{
49
		$count = substr_count($domain, '*');
50
		foreach (explode('*', $domain) as $e)
51
		{
52
			if (empty($e))
53
				continue;
54
55
			if (strpos($url, $e) === false)
56
				return false;
57
			$url = str_replace($e, '@', $url);
58
		}
59
60
		$params = [];
61
		foreach (explode('@', $url) as $t)
62
		{
63
			if (!empty($t))
64
				$params[] = $t;
65
		}
66
67
		return ($count === count($params));
68
	}
69
70
}
71