Passed
Push — trunk ( 60c287...522604 )
by Christian
21:52 queued 08:22
created

StaticSystemConfigService   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 27
c 1
b 0
f 0
dl 0
loc 74
rs 10
wmc 14

5 Methods

Rating   Name   Duplication   Size   Complexity  
A set() 0 9 2
B lookupValue() 0 35 7
A get() 0 7 2
A setMultiple() 0 4 2
A __construct() 0 2 1
1
<?php declare(strict_types=1);
2
3
namespace Shopware\Core\Test\Stub\SystemConfigService;
4
5
use Shopware\Core\System\SystemConfig\SystemConfigService;
6
7
/**
8
 * @final
9
 */
10
class StaticSystemConfigService extends SystemConfigService
11
{
12
    /**
13
     * @param array<string, mixed> $config
14
     */
15
    public function __construct(private array $config = [])
16
    {
17
    }
18
19
    public function get(string $key, ?string $salesChannelId = null)
20
    {
21
        if ($salesChannelId) {
22
            return $this->lookupValue($this->config[$salesChannelId] ?? [], $key);
23
        }
24
25
        return $this->lookupValue($this->config, $key);
26
    }
27
28
    public function set(string $key, $value, ?string $salesChannelId = null): void
29
    {
30
        if ($salesChannelId) {
31
            $this->config[$salesChannelId][$key] = $value;
32
33
            return;
34
        }
35
36
        $this->config[$key] = $value;
37
    }
38
39
    public function setMultiple(array $values, ?string $salesChannelId = null): void
40
    {
41
        foreach ($values as $k => $v) {
42
            $this->set($k, $v, $salesChannelId);
43
        }
44
    }
45
46
    /**
47
     * @param array<string, mixed> $param
48
     */
49
    private function lookupValue(array $param, string $key): mixed
50
    {
51
        if (\array_key_exists($key, $param)) {
52
            return $param[$key];
53
        }
54
55
        // Look for sub keys
56
        $foundValues = [];
57
        $prefix = rtrim($key, '.');
58
        foreach ($param as $configKey => $configValue) {
59
            if (!str_starts_with($configKey, $prefix)) {
60
                continue;
61
            }
62
63
            $formattedKey = substr($configKey, \strlen($prefix) + 1);
64
65
            $pointer = &$foundValues;
66
            foreach (explode('.', $formattedKey) as $part) {
67
                // @phpstan-ignore-next-line
68
                if (!\array_key_exists($part, $pointer)) {
69
                    $pointer[$part] = [];
70
                }
71
72
                $pointer = &$pointer[$part];
73
            }
74
            $pointer = $configValue;
75
        }
76
77
        // @phpstan-ignore-next-line
78
        if (empty($foundValues)) {
79
            return null;
80
        }
81
82
        // @phpstan-ignore-next-line
83
        return $foundValues;
84
    }
85
}
86