-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathDiffSorter.php
More file actions
108 lines (82 loc) · 2.77 KB
/
DiffSorter.php
File metadata and controls
108 lines (82 loc) · 2.77 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
99
100
101
102
103
104
105
106
107
108
<?php namespace DBDiff\SQLGen;
class DiffSorter {
private $up_order = [
"SetDBCharset",
"SetDBCollation",
"AddTable",
"DeleteData",
"DropTable",
"AlterTableEngine",
"AlterTableCollation",
"AlterTableAddColumn",
"AlterTableChangeColumn",
"AlterTableDropColumn",
"AlterTableAddKey",
"AlterTableChangeKey",
"AlterTableDropKey",
"AlterTableAddConstraint",
"AlterTableChangeConstraint",
"AlterTableDropConstraint",
"InsertData",
"UpdateData"
];
private $down_order = [
"SetDBCharset",
"SetDBCollation",
"InsertData",
"AddTable",
"DropTable",
"AlterTableEngine",
"AlterTableCollation",
"AlterTableAddColumn",
"AlterTableChangeColumn",
"AlterTableDropColumn",
"AlterTableAddKey",
"AlterTableChangeKey",
"AlterTableDropKey",
"AlterTableAddConstraint",
"AlterTableChangeConstraint",
"AlterTableDropConstraint",
"DeleteData",
"UpdateData"
];
public function sort($diff, $type) {
usort($diff, [$this, 'compare'.ucfirst($type)]);
return $diff;
}
private function compareUp($a, $b) {
return $this->compare($this->up_order, $a, $b);
}
private function compareDown($a, $b) {
return $this->compare($this->down_order, $a, $b);
}
private function compare($order, $a, $b) {
$orderMap = array_flip($order);
$reflectionA = new \ReflectionClass($a);
$reflectionB = new \ReflectionClass($b);
$sqlGenClassA = $reflectionA->getShortName();
$sqlGenClassB = $reflectionB->getShortName();
$indexA = $orderMap[$sqlGenClassA];
$indexB = $orderMap[$sqlGenClassB];
if ($indexA === $indexB) {
// Secondary sort by table name if available
$tableA = $a->table ?? '';
$tableB = $b->table ?? '';
if ($tableA !== $tableB) {
return strcmp($tableA, $tableB);
}
// Tertiary sort by item (column, key, etc.) if available
$itemA = $a->column ?? $a->key ?? $a->name ?? '';
$itemB = $b->column ?? $b->key ?? $b->name ?? '';
if ($itemA !== $itemB) {
return strcmp((string)$itemA, (string)$itemB);
}
// Quaternary sort by data keys if it's a data diff
if (is_array($a->diff) && isset($a->diff['keys']) && is_array($b->diff) && isset($b->diff['keys'])) {
return strcmp(json_encode($a->diff['keys']), json_encode($b->diff['keys']));
}
return 0;
}
return ($indexA > $indexB) ? 1 : -1;
}
}