ScopeCollection::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Thinktomorrow\Locale;
4
5
use Thinktomorrow\Locale\Values\Config;
6
use Thinktomorrow\Locale\Values\Root;
7
8
final class ScopeCollection
9
{
10
    /**
11
     * @var Config
12
     */
13
    private $config;
14
15 87
    private function __construct(Config $config)
16
    {
17 87
        $this->config = $config;
18 87
    }
19
20 17
    public static function fromArray(array $config)
21
    {
22 17
        return new static(Config::from($config));
23
    }
24
25 76
    public static function fromConfig(Config $config)
26
    {
27 76
        return new static($config);
28
    }
29
30 85
    public function findByRoot(string $root): Scope
31
    {
32 85
        return $this->findByKey($this->guessKeyFromRoot($root));
33
    }
34
35
    /**
36
     * @param string $locale
37
     *
38
     * @return null|Scope
39
     */
40 12
    public function findCanonical(string $locale): ?Scope
41
    {
42 12
        $canonicals = $this->config->get('canonicals');
43
44 12
        if (!isset($canonicals[$locale])) {
45 3
            return null;
46
        }
47
48 11
        $scope = $this->findByRoot($canonicals[$locale]);
49
50 11
        return $scope->setCustomRoot(Root::fromString($canonicals[$locale]));
51
    }
52
53 85
    private function guessKeyFromRoot(string $value): string
54
    {
55 85
        foreach ($this->config->get('locales') as $scopeKey => $locales) {
56 85
            $pattern = preg_quote($scopeKey, '#');
57
58
            /*
59
             * The host pattern allows for an asterix which stands for a
60
             * wildcard of characters when matching the scope keys.
61
             * The default '*' scope will match anything
62
             */
63 85
            if (false !== strpos($pattern, '*')) {
64 30
                $pattern = str_replace('\*', '(.+)', $pattern);
65
            }
66
67 85
            if (preg_match("#^(https?://)?(www\.)?$pattern/?$#", $value)) {
68 84
                return $scopeKey;
69
            }
70
        }
71
72
        // In case value remains empty, we return the default routing.
73 1
        return '*';
74
    }
75
76
    // We limit the available locales to the current domain space, including the default ones
77 85
    private function findByKey(string $scopeKey): Scope
78
    {
79 85
        $locales = $this->config->get('locales');
80
81 85
        $locales = array_merge($locales['*'], $locales[$scopeKey]);
82
83
        // We flip our values so in case of duplicate locales, the default one
84
        // is omitted and the one from the specific scope is preserved.
85 85
        return new Scope(array_flip(array_flip($locales)));
86
    }
87
}
88