ConfigProvider::__invoke()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 0
dl 0
loc 13
rs 10
c 0
b 0
f 0
1
<?php
2
3
4
namespace PFlorek\AwsParameterStore;
5
6
7
use Aws\Ssm\SsmClient;
8
use function PFlorek\Elevator\array_elevate;
9
10
class ConfigProvider
11
{
12
    /**
13
     * @var Options
14
     */
15
    private $options;
16
17
    /**
18
     * @var Reader
19
     */
20
    private $reader;
21
22
    /**
23
     * @var string[]
24
     */
25
    private $profiles;
26
27
    /**
28
     * @param array|SsmClient|Reader $client
29
     * @param string[]|Options $options
30
     * @param null|string|string[] $profiles
31
     */
32
    public function __construct($client, $options, $profiles = [])
33
    {
34
        if (is_array($options)) {
35
            $options = Options::create($options);
36
        }
37
        $this->options = $options;
38
39
        if(!$client instanceof Reader) {
40
            $client = new Reader($client);
41
        }
42
        $this->reader = $client;
43
44
        $this->profiles = (array)$profiles;
45
    }
46
47
    /**
48
     * @return string[]|int[]|float[]|bool[]
49
     */
50
    public function __invoke(): array
51
    {
52
        $paths = $this->createPaths($this->profiles);
53
        $paths = array_reverse($paths);
54
55
        $config = [];
56
        foreach ($paths as $context) {
57
            $config += $this->reader->fromPath($context);
58
        }
59
60
        $config = array_map([SimpleCast::class, 'cast'], $config);
61
62
        return array_elevate($config);
63
    }
64
65
    /**
66
     * @param string[] $profiles
67
     * @return string[]
68
     */
69
    private function createPaths(array $profiles): array
70
    {
71
        $prefix = $this->options->getPrefix();
72
        $prefix = trim($prefix, '/');
73
74
        $sharedContext = $this->options->getSharedContext();
75
        $sharedContext = trim($sharedContext, '/');
76
77
        $name = $this->options->getApplicationName();
78
        $name = trim($name, '/');
79
80
        $separator = $this->options->getProfileSeparator();
81
82
        $paths = [];
83
        if ($sharedContext) {
84
            $paths[] = "/{$prefix}/{$sharedContext}";
85
        }
86
87
        $paths[] = "/{$prefix}/{$name}"; // base context
88
89
        foreach ($profiles as $profile) {
90
            $profile = trim($profile, '/');
91
            $paths[] = "/{$prefix}/{$name}{$separator}{$profile}";
92
        }
93
94
        return $paths;
95
    }
96
}