-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVersionManager.php
More file actions
98 lines (79 loc) · 2.89 KB
/
VersionManager.php
File metadata and controls
98 lines (79 loc) · 2.89 KB
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
<?php
namespace Andrey\StuffVersioned;
use Psr\Log\LoggerInterface;
use Throwable;
class VersionManager implements VersionManagerInterface
{
/** @var VersionInterface[] */
protected array $versions = [];
public function __construct(
private readonly BackendInterface $backend,
private readonly ?LoggerInterface $logger = null,
) {
}
public function addVersion(VersionInterface $v): void
{
$this->versions[] = clone $v;
}
public function withVersion(VersionInterface $v): self
{
$new = clone $this;
$new->addVersion($v);
return $new;
}
/** @return int representing the counter of versions executed */
public function run(): int
{
$currentVersion = $this->backend->getCurrentVersionId();
$versionRuns = $this->backend->getVersionList();
$indexForLastVersionExecuted = -1;
foreach ($this->versions as $i => $version) {
if ($version->getId() === $currentVersion) {
$indexForLastVersionExecuted = $i;
break;
}
if ($version->check() === false) {
continue;
}
if (isset($versionRuns[$i]) && $versionRuns[$i]->versionId !== $version->getId()) {
$this->logger?->warning("Inconsistent versioning, found {$version->getId()} expected {$versionRuns[$i]->versionId} as {$i}th run");
}
}
// Move to next version
$currentVersionToExecute = $indexForLastVersionExecuted + 1;
$versionsAvailable = count($this->versions);
// Already on latest version
if ($currentVersionToExecute === $versionsAvailable) {
$this->logger?->debug(
'Already on latest version',
);
return 0;
}
// Invalid configuration
if ($currentVersionToExecute > $versionsAvailable) {
$this->logger?->warning('Number of versions executed exceeds available ones');
return 0;
}
$counter = 0;
for (; $currentVersionToExecute < $versionsAvailable; $currentVersionToExecute++) {
$version = $this->versions[$currentVersionToExecute];
if ($version->check() === false) {
continue;
}
$entry = $this->backend->markVersionAsProcessing($version->getId());
try {
$version->run();
$this->backend->markVersionAsSuccessful($entry);
$counter++;
} catch (Throwable $exception) {
$this->logger?->warning(
"Version run failed with exception {$exception->getMessage()}",
);
$version->rollback();
$this->backend->abortVersionProcessing($entry, $exception->getMessage());
break;
}
}
return $counter;
}
}