-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClassifier.php
More file actions
91 lines (72 loc) · 2.62 KB
/
Copy pathClassifier.php
File metadata and controls
91 lines (72 loc) · 2.62 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
<?php
declare(strict_types=1);
namespace StageGate;
final class Classifier
{
/**
* @param Row[] $stagedRows
* @param Row[] $existingRows keyed by row key
* @param FieldGroup[] $fieldGroups
* @return ClassifiedRow[]
*/
public static function classifyAll(array $stagedRows, array $existingRows, array $fieldGroups): array
{
$existingByKey = [];
foreach ($existingRows as $row) {
$existingByKey[$row->key] = $row;
}
$stagedKeys = [];
$classified = [];
foreach ($stagedRows as $staged) {
$stagedKeys[$staged->key] = true;
$classified[] = self::classifyRow($staged, $existingByKey[$staged->key] ?? null, $fieldGroups);
}
foreach ($existingRows as $existing) {
if (isset($stagedKeys[$existing->key])) {
continue;
}
$fieldChanges = array_map(
fn (string $field) => new FieldChange($field, $existing->get($field), null),
array_keys($existing->data),
);
$classified[] = new ClassifiedRow($existing, ChangeClass::Removed, $fieldChanges);
}
return $classified;
}
/** @param FieldGroup[] $fieldGroups */
public static function classifyRow(Row $staged, ?Row $existing, array $fieldGroups): ClassifiedRow
{
if ($existing === null) {
$fieldChanges = array_map(
fn (string $field) => new FieldChange($field, null, $staged->get($field)),
array_keys($staged->data),
);
return new ClassifiedRow($staged, ChangeClass::New, $fieldChanges);
}
$fieldChanges = [];
$riskChanged = false;
$anyChanged = false;
foreach ($fieldGroups as $group) {
$groupChanged = false;
foreach ($group->fields as $field) {
$oldValue = $existing->get($field);
$newValue = $staged->get($field);
if ($oldValue === $newValue) {
continue;
}
$fieldChanges[] = new FieldChange($field, $oldValue, $newValue);
$groupChanged = true;
}
if ($groupChanged) {
$anyChanged = true;
$riskChanged = $riskChanged || $group->isRisk;
}
}
$changeClass = match (true) {
$riskChanged => ChangeClass::OverwriteRisk,
$anyChanged => ChangeClass::Updated,
default => ChangeClass::Unchanged,
};
return new ClassifiedRow($staged, $changeClass, $fieldChanges);
}
}