forked from aws-samples/aws-php-sample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVersionsRemover.php
126 lines (108 loc) · 3.12 KB
/
VersionsRemover.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
<?php
use Aws\ElasticBeanstalk\ElasticBeanstalkClient;
final class VersionsRemover
{
/**
* @var array
*/
protected $config;
/**
* @var ElasticBeanstalkClient
*/
protected $client;
public function __construct($config)
{
$requiredKeys = [
'client',
'labelPatterns',
'leaveLastNVersions'
];
foreach ($requiredKeys as $key) {
if (!isset($config[$key])) {
throw new \Exception(sprintf('Missing "%s" configuration', $key));
}
}
$this->config = $config;
}
/**
* return int
*/
public function perform()
{
$applicationVersions = $this->getApplicationVersions();
$applicationVersions = $this->removeCurrentUsedApplicationVersions($applicationVersions);
$applicationVersions = $this->removeRecentVersions($applicationVersions);
foreach ($applicationVersions as $version) {
$this->getClient()->deleteApplicationVersion([
'ApplicationName' => $version['ApplicationName'],
'VersionLabel' => $version['VersionLabel'],
]);
}
return 0;
}
/**
* @return array
*/
protected function getApplicationVersions()
{
$response = $this->getClient()->describeApplicationVersions();
$response = $response->getAll();
return $response['ApplicationVersions'];
}
/**
* @param array $applicationVersions
*
* @return array
*/
protected function removeCurrentUsedApplicationVersions($applicationVersions)
{
$environments = $this->getEnvironments();
foreach($environments as $environment) {
foreach ($applicationVersions as $key => $version) {
if($version['VersionLabel'] == $environment['VersionLabel']) {
unset($applicationVersions[$key]);
break;
}
}
}
return $applicationVersions;
}
/**
* @return array
*/
protected function getEnvironments()
{
$response = $this->getClient()->describeEnvironments();
$response = $response->getAll();
return $response['Environments'];
}
/**
* @param array $applicationVersions
*
* @return array
*/
protected function removeRecentVersions($applicationVersions)
{
foreach($this->config['labelPatterns'] as $pattern) {
$counter = 0;
foreach ($applicationVersions as $key => $version) {
if (preg_match($pattern, $version['VersionLabel'])) {
if ($counter++ < $this->config['leaveLastNVersions']) {
unset($applicationVersions[$key]);
}
}
}
}
return $applicationVersions;
}
/**
* @return ElasticBeanstalkClient
*/
protected function getClient()
{
if (!$this->client) {
$this->client = ElasticBeanstalkClient::factory($this->config['client']);
}
return $this->client;
}
}