Passed
Push — master ( f16e80...a7744a )
by Patrick
03:41
created

Reader::getParameters()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 2
nop 1
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 $client
18
     */
19
    public function __construct(SsmClient $client)
20
    {
21
        $this->client = $client;
22
    }
23
24
    /**
25
     * @see https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ssm-2014-11-06.html#getparametersbypath
26
     * @param string $path
27
     * @return mixed[]
28
     */
29
    public function read(string $path): array
30
    {
31
        $config = [];
32
        foreach ($this->getParameters($path) as $parameter) {
33
            $name = $parameter['Name'];
34
            $name = str_replace(["{$path}/", '/'], ['', '.'], $name);
35
            $value = $parameter['Value'];
36
            $config[$name] = $value;
37
        }
38
39
        return $config;
40
    }
41
42
    /**
43
     * @param string $path
44
     * @return Generator|string[][]
45
     */
46
    private function getParameters(string $path)
47
    {
48
        $nextToken = null;
49
        do {
50
            $result = $this->getParametersByPath($path, $nextToken);
51
            $parameters = $result['Parameters'];
52
53
            foreach ($parameters as $parameter) {
54
                yield $parameter;
55
            }
56
57
            $nextToken = $result['NextToken'] ?? null;
58
        } while ($nextToken);
59
    }
60
61
    /**
62
     * @see https://docs.aws.amazon.com/de_de/systems-manager/latest/APIReference/API_GetParametersByPath.html#API_GetParametersByPath_RequestParameters
63
     *
64
     * @param string $path
65
     * @param string|null $nextToken
66
     * @return Result|mixed
67
     */
68
    private function getParametersByPath(string $path, string $nextToken = null)
69
    {
70
        $args = [
71
            'Path' => $path,
72
            'Recursive' => true,
73
            'WithDecryption' => true,
74
        ];
75
76
        if ($nextToken) {
77
            $args['NextToken'] = $nextToken;
78
        }
79
80
        return $this->client->getParametersByPath($args);
81
    }
82
}