Reader::getParametersByPath()   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 2
dl 0
loc 13
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PFlorek\AwsParameterStore;
4
5
use Aws\Result;
6
use Aws\Ssm\SsmClient;
7
use Generator;
8
9
class Reader
10
{
11
    /**
12
     * @var SsmClient
13
     */
14
    private $client;
15
16
    /**
17
     * @param SsmClient|array $client
18
     */
19
    public function __construct($client)
20
    {
21
        if (is_array($client)) {
22
            $client = new SsmClient($client);
23
        }
24
25
        $this->client = $client;
26
    }
27
28
    /**
29
     * @see https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ssm-2014-11-06.html#getparametersbypath
30
     * @param string $path
31
     * @return mixed[]
32
     */
33
    public function fromPath(string $path): array
34
    {
35
        $config = [];
36
        foreach ($this->getParameters($path) as $parameter) {
37
            $name = $parameter['Name'];
38
            $name = str_replace(["{$path}/", '/'], ['', '.'], $name);
39
            $value = $parameter['Value'];
40
            $config[$name] = $value;
41
        }
42
43
        return $config;
44
    }
45
46
    /**
47
     * @param string $path
48
     * @return Generator|string[][]
49
     */
50
    private function getParameters(string $path)
51
    {
52
        $nextToken = null;
53
        do {
54
            $result = $this->getParametersByPath($path, $nextToken);
55
            $parameters = $result['Parameters'];
56
57
            foreach ($parameters as $parameter) {
58
                yield $parameter;
59
            }
60
61
            $nextToken = $result['NextToken'] ?? null;
62
        } while ($nextToken);
63
    }
64
65
    /**
66
     * @see https://docs.aws.amazon.com/de_de/systems-manager/latest/APIReference/API_GetParametersByPath.html#API_GetParametersByPath_RequestParameters
67
     *
68
     * @param string $path
69
     * @param string|null $nextToken
70
     * @return Result|mixed
71
     */
72
    private function getParametersByPath(string $path, string $nextToken = null)
73
    {
74
        $args = [
75
            'Path' => $path,
76
            'Recursive' => true,
77
            'WithDecryption' => true,
78
        ];
79
80
        if ($nextToken) {
81
            $args['NextToken'] = $nextToken;
82
        }
83
84
        return $this->client->getParametersByPath($args);
85
    }
86
}