-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate.php
More file actions
331 lines (297 loc) · 12 KB
/
Copy pathmigrate.php
File metadata and controls
331 lines (297 loc) · 12 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
<?php
declare(strict_types=1);
/**
* Data Validation Testing Migration Script
*
* This script helps to migrate an application from orca-services/cakephp-data-validation-testing 2.x to 3.x.
*
* It follows the migration guide:
* https://github.com/orca-services/cakephp-data-validation-testing/blob/cakephp-5.x/docs/Migration.md
*
* What it does:
* 1. Renames all calls of the old `testDataValidation`-prefixed trait methods to the new `assertValidation`-prefixed ones.
* 2. Replaces calls of the removed `testRules()` with `assertRules()` and lists them for manual review.
* 3. Lists all calls of rule-dedicated methods, which now only check their own rule, for manual review.
*
* Usage: php vendor/orca-services/cakephp-data-validation-testing/migrate.php (from your application root)
*/
define('COL_DESCRIPTION', 0);
define('COL_HELP', 1);
define('COL_DEFAULT', 2);
define('PACKAGE_NAME', 'orca-services/cakephp-data-validation-testing');
$fields = [
'paths' => [
'Directories to migrate',
'comma separated, relative to ' . getcwd(),
'tests,plugins',
],
];
/**
* Old method name => new method name
*
* Section 1 of the migration guide.
*/
$renames = [
'testDataValidationNotEmpty' => 'assertValidationNotEmpty',
'testDataValidationEmpty' => 'assertValidationEmpty',
'testDataValidationRequired' => 'assertValidationRequired',
'testDataValidationNotRequired' => 'assertValidationNotRequired',
'testDataValidationBoolean' => 'assertValidationBoolean',
'testDataValidationURLWithProtocol' => 'assertValidationURLWithProtocol',
'testDataValidationDateTime' => 'assertValidationDateTime',
'testDataValidationDate' => 'assertValidationDate',
'testDataValidationInList' => 'assertValidationInList',
'testDataValidation' => 'assertValidation',
'testDataValidationNoErrors' => 'assertValidationNoErrors',
'testFullDataValidation' => 'assertValidationTableErrors',
'testFullDataValidationNoErrors' => 'assertValidationTableNoErrors',
'testDataValidationContains' => 'assertValidationContains',
'testDataValidationNotContains' => 'assertValidationNotContains',
'assertDataValidationErrorsContain' => 'assertValidationErrorsContain',
'testDataValidationListContains' => 'assertValidationListContains',
'testDataValidationListNotContains' => 'assertValidationListNotContains',
'testDataRules' => 'assertRules',
// Removed, assertRules() is the replacement. See $manualReviewRenames.
'testRules' => 'assertRules',
'testDataRulesNoErrors' => 'assertRulesNoErrors',
'testDataValidationMaxLength' => 'assertValidationMaxLength',
'testDataValidationMinLength' => 'assertValidationMinLength',
'testDataValidationScalar' => 'assertValidationScalar',
'testDataValidationDecimal' => 'assertValidationDecimal',
'testDataValidationInteger' => 'assertValidationInteger',
'testDataValidationNonNegativeInteger' => 'assertValidationNonNegativeInteger',
'testDataValidationGreaterThanOrEqual' => 'assertValidationGreaterThanOrEqual',
'testDataValidationEmail' => 'assertValidationEmail',
'testDataValidationUuid' => 'assertValidationUuid',
'testDataValidationLengthBetween' => 'assertValidationLengthBetween',
'testDataValidationRange' => 'assertValidationRange',
'testDataValidationNaturalNumber' => 'assertValidationNaturalNumber',
'testDataValidationForeignKey' => 'assertValidationForeignKey',
'testDataValidationIsUnique' => 'assertValidationIsUnique',
];
/**
* Old method names whose replacement does not behave exactly the same, with the reason
*/
$manualReviewRenames = [
'testRules' => 'testRules() was removed. assertRules() skips data validation (validate => false) '
. 'and asserts that saving fails, while testRules() asserted that there are no validation errors first.',
];
/**
* Rule-dedicated methods, which now only check their own rule (section 2 of the migration guide)
*/
$ruleDedicatedMethods = [
'assertValidationNotEmpty',
'assertValidationEmpty',
'assertValidationRequired',
'assertValidationNotRequired',
'assertValidationBoolean',
'assertValidationURLWithProtocol',
'assertValidationDateTime',
'assertValidationDate',
'assertValidationMaxLength',
'assertValidationMinLength',
'assertValidationScalar',
'assertValidationDecimal',
'assertValidationInteger',
'assertValidationNonNegativeInteger',
'assertValidationGreaterThanOrEqual',
'assertValidationEmail',
'assertValidationUuid',
'assertValidationLengthBetween',
'assertValidationRange',
'assertValidationNaturalNumber',
];
$values = [];
function read_from_console($prompt)
{
if (function_exists('readline')) {
$line = trim(readline($prompt));
if (!empty($line)) {
readline_add_history($line);
}
} else {
echo $prompt;
$line = trim(fgets(STDIN));
}
return $line;
}
/**
* Build the regular expression matching calls/references of the given method names
*
* Only matches names directly preceded by "->" or "::", so that e.g. own test methods named alike are not touched.
* The longest names come first and a word boundary is enforced, so `testDataValidation` never matches a longer name.
*/
function method_call_pattern(array $methodNames)
{
usort($methodNames, static function ($a, $b) {
return strlen($b) - strlen($a);
});
$alternatives = implode('|', array_map(static function ($name) {
return preg_quote($name, '/');
}, $methodNames));
return '/(->|::)(\s*)(' . $alternatives . ')\b/';
}
/**
* Find all PHP files in the given directories
*/
function find_php_files(array $paths)
{
$files = [];
foreach ($paths as $path) {
if (is_file($path) && substr($path, -4) === '.php') {
$files[] = $path;
continue;
}
if (!is_dir($path)) {
echo "Warning: '$path' does not exist, skipping.\n";
continue;
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
);
foreach ($iterator as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
$files[] = $file->getPathname();
}
}
}
sort($files);
return array_unique($files);
}
/**
* Get the line number of a byte offset within a text
*/
function line_of($text, $offset)
{
return substr_count($text, "\n", 0, $offset) + 1;
}
$modify = 'n';
do {
if ($modify == 'q') {
exit;
}
$values = [];
echo "----------------------------------------------------------------------\n";
echo 'Migration of ' . PACKAGE_NAME . " to 3.x\n";
echo "Please, provide the following information:\n";
echo "----------------------------------------------------------------------\n";
foreach ($fields as $fieldKey => $field) {
$default = $field[COL_DEFAULT] ?? '';
$prompt = sprintf(
'%s%s%s: ',
$field[COL_DESCRIPTION],
$field[COL_HELP] ? ' (' . $field[COL_HELP] . ')' : '',
$default !== '' ? ' [' . $default . ']' : '',
);
$values[$fieldKey] = read_from_console($prompt);
if (empty($values[$fieldKey])) {
$values[$fieldKey] = $default;
}
}
echo "\n";
echo "----------------------------------------------------------------------\n";
echo "Please, check that everything is correct:\n";
echo "----------------------------------------------------------------------\n";
foreach ($fields as $fieldKey => $field) {
echo $field[COL_DESCRIPTION] . ": $values[$fieldKey]\n";
}
echo "\n";
} while (($modify = strtolower(read_from_console('Migrate files with these values? [y/N/q] '))) !== 'y');
echo "\n";
$paths = array_filter(array_map('trim', explode(',', $values['paths'])));
$filesToMigrate = find_php_files($paths);
$renamePattern = method_call_pattern(array_keys($renames));
$ruleDedicatedPattern = method_call_pattern($ruleDedicatedMethods);
$leftoverPattern = '/\b(' . implode('|', array_map(static function ($name) {
return preg_quote($name, '/');
}, array_keys($renames))) . ')\b/';
$totalReplacements = 0;
$changedFiles = 0;
$manualReview = [];
$ruleDedicatedCalls = [];
$leftovers = [];
echo "----------------------------------------------------------------------\n";
echo "Renaming methods:\n";
echo "----------------------------------------------------------------------\n";
foreach ($filesToMigrate as $filename) {
$contentToReplaceIn = file_get_contents($filename);
// Collect the calls that need a manual review, before replacing them
if (preg_match_all($renamePattern, $contentToReplaceIn, $matches, PREG_OFFSET_CAPTURE)) {
foreach ($matches[3] as $match) {
if (isset($manualReviewRenames[$match[0]])) {
$manualReview[] = sprintf(
'%s:%d: %s',
$filename,
line_of($contentToReplaceIn, $match[1]),
$manualReviewRenames[$match[0]],
);
}
}
}
$count = 0;
$migratedContent = preg_replace_callback(
$renamePattern,
static function ($match) use ($renames) {
return $match[1] . $match[2] . $renames[$match[3]];
},
$contentToReplaceIn,
-1,
$count,
);
if ($count > 0) {
file_put_contents($filename, $migratedContent);
echo "$filename: $count replacement(s)\n";
$totalReplacements += $count;
$changedFiles++;
}
// Rule-dedicated methods now only check their own rule
if (preg_match_all($ruleDedicatedPattern, $migratedContent, $matches, PREG_OFFSET_CAPTURE)) {
foreach ($matches[3] as $match) {
$ruleDedicatedCalls[] = sprintf(
'%s:%d: %s()',
$filename,
line_of($migratedContent, $match[1]),
$match[0],
);
}
}
// Old names still present, e.g. in strings, callables or own method definitions
if (preg_match_all($leftoverPattern, $migratedContent, $matches, PREG_OFFSET_CAPTURE)) {
foreach ($matches[1] as $match) {
$leftovers[] = sprintf(
'%s:%d: %s',
$filename,
line_of($migratedContent, $match[1]),
$match[0],
);
}
}
}
echo "\n$totalReplacements replacement(s) in $changedFiles of " . count($filesToMigrate) . " file(s).\n\n";
echo "Done.\n\n";
if (!empty($manualReview)) {
echo "----------------------------------------------------------------------\n";
echo "Please, review these replacements manually:\n";
echo "----------------------------------------------------------------------\n";
echo implode("\n", $manualReview) . "\n\n";
}
if (!empty($leftovers)) {
echo "----------------------------------------------------------------------\n";
echo "Old method names that were not replaced automatically:\n";
echo "(e.g. in strings, callables or own methods with the same name)\n";
echo "----------------------------------------------------------------------\n";
echo implode("\n", $leftovers) . "\n\n";
}
if (!empty($ruleDedicatedCalls)) {
echo "----------------------------------------------------------------------\n";
echo "Rule-dedicated methods now check only their own rule.\n";
echo "Previously the entire error array of the field was compared, which could hide\n";
echo "unrelated errors. Please, check that these tests still cover what you intend,\n";
echo "especially where a custom \$expected with several rules is passed:\n";
echo "----------------------------------------------------------------------\n";
echo implode("\n", $ruleDedicatedCalls) . "\n\n";
}
echo "\nNext steps:\n";
echo "- Run your test suite and fix failing tests.\n";
echo "- Review the diff (e.g. git diff) before committing.\n\n";
echo "See https://github.com/orca-services/cakephp-data-validation-testing/blob/cakephp-5.x/docs/Migration.md\n";