-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathprefix-vendor-namespace.php
executable file
·464 lines (409 loc) · 11.8 KB
/
prefix-vendor-namespace.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
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
#!/usr/bin/env php
<?php
declare( strict_types=1 );
// Disable phpcs rules which are not relevant to a dev script.
// phpcs:disable WordPress.Security.EscapeOutput
// phpcs:disable WordPress.WP.AlternativeFunctions
/*
* List of packages to prefix the namespace.
*
* namespace = Namespace to search for.
* extra_namespaces = Additional namespaces to search and prefix (optional).
* package = Full name of package in the vendor folder.
* strict = When true it will search matching the full namespace, false will allow matching of a namespace prefix.
* exclude_autoload = Array of autoload files which are not required to be included in the main composer file (optional).
*/
$packages = [
[
'namespace' => 'Psr\\Http\\Client',
'package' => 'psr/http-client',
'strict' => false,
],
[
'namespace' => 'Psr\\Http\\Message',
'package' => 'psr/http-message',
'strict' => false,
],
[
'namespace' => 'Psr\\Http\\Message',
'package' => 'psr/http-factory',
'strict' => false,
],
[
'namespace' => 'Psr\\Container',
'package' => 'psr/container',
'strict' => false,
],
[
'namespace' => 'League\\Container',
'package' => 'league/container',
'strict' => false,
],
[
'namespace' => 'League\\ISO3166',
'package' => 'league/iso3166',
'strict' => false,
],
[
'namespace' => 'Google',
'extra_namespaces' => [
'Google\\AuthHandler',
'Google\\AccessToken',
'Google\\Http',
'Google\\Service',
'Google\\Task',
'Google\\Utils',
],
'package' => 'google/apiclient',
'strict' => true,
'exclude_autoload' => [ 'src/aliases.php' ],
],
[
'namespace' => 'Google\\Service',
'package' => 'google/apiclient-services',
'strict' => false,
'exclude_autoload' => [ 'autoload.php' ],
],
[
'namespace' => 'Google\\Auth',
'package' => 'google/auth',
'strict' => false,
],
[
'namespace' => 'GuzzleHttp',
'package' => 'guzzlehttp',
'strict' => false,
],
];
$vendor_dir = dirname( __DIR__ ) . '/vendor';
$namespace_prefix = 'Automattic\\WooCommerce\\GoogleListingsAndAds\\Vendor';
// Vendor libraries which are dependent on a library we are prefixing.
$dependencies = [
'google/apiclient' => [
'google/apiclient-services',
],
'google/auth' => [
'google/apiclient',
'google/gax',
],
'guzzlehttp' => [
'google/apiclient',
'google/auth',
'google/gax',
],
'psr/container' => [
'league/container',
],
'psr/http-client' => [
'firebase/php-jwt',
'guzzlehttp/guzzle',
],
'psr/http-message' => [
'google/apiclient',
'google/auth',
'google/gax',
'guzzlehttp/guzzle',
'guzzlehttp/psr7',
'psr/http-client',
],
'psr/http-factory' => [
'firebase/php-jwt',
'guzzlehttp/psr7',
],
];
// Namespaces which are used directly within the code.
$direct_replacements = [
'guzzlehttp' => [
'GuzzleHttp\Client(',
'GuzzleHttp\ClientInterface::MAJOR_VERSION',
'GuzzleHttp\ClientInterface::VERSION',
'GuzzleHttp\describe_type',
'GuzzleHttp\HandlerStack::create',
'GuzzleHttp\Message\ResponseInterface)',
'GuzzleHttp\Psr7\Message::bodySummary',
'GuzzleHttp\Psr7\Utils::streamFor',
'GuzzleHttp\Psr7\Utils::tryFopen',
],
];
// Read our composer.json file into an array.
$composer_json = json_decode( file_get_contents( dirname( __DIR__ ) . '/composer.json' ), true );
foreach ( $packages as $package ) {
// Process namespaces and uses in all package files.
foreach ( find_files( $package['package'] ) as $file ) {
process_file( $file, $package, true, true );
}
// Process only uses in dependent package files.
foreach ( find_dependent_files( $package['package'] ) as $file ) {
process_file( $file, $package, false, true );
}
// Prefix autoloads and remove file autoloads from vendor/composer/installed.json
update_autoloads(
"{$vendor_dir}/composer/installed.json",
$composer_json['autoload']['files'] ?? [],
$package
);
}
/**
* Process prefixing in a specific file.
*
* @since 2.3.9
*
* @param string $file File name.
* @param array $package Package prefix configuration.
* @param bool $prefix_namespace Whether to prefix namespaces or not.
* @param bool $prefix_uses Whether to prefix uses of a namespace.
*/
function process_file( $file, $package, $prefix_namespace = true, $prefix_uses = false ) {
global $direct_replacements;
$contents = file_get_contents( $file );
$content_hash = md5( $contents );
if ( $prefix_namespace ) {
prefix_namespace( $contents, $package );
}
if ( $prefix_uses ) {
prefix_uses( $contents, $package );
if ( ! empty( $direct_replacements[ $package['package'] ] ) ) {
foreach ( $direct_replacements[ $package['package'] ] as $search ) {
prefix_string( $contents, $search );
}
}
}
// Only overwrite file if the contents have changed.
if ( $content_hash !== md5( $contents ) ) {
file_put_contents( $file, $contents );
}
}
/**
* Prefix the namespace.
*
* @since 2.3.9
*
* @param string $contents File contents.
* @param array $package Package prefix configuration.
*/
function prefix_namespace( &$contents, $package ) {
global $namespace_prefix;
$quoted = preg_quote( $package['namespace'], '#' );
// Match only the full namespace when strict is enabled.
if ( $package['strict'] ) {
$regex = "#^(\s*)(namespace)\s*({$quoted};)#m";
} else {
$regex = "#^(\s*)(namespace)\s*({$quoted}[\\\\|;])#m";
}
$contents = preg_replace(
$regex,
"\$1\$2 {$namespace_prefix}\\\\\$3",
$contents
);
if ( $package['strict'] && ! empty( $package['extra_namespaces'] ) ) {
foreach ( $package['extra_namespaces'] as $namespace ) {
prefix_namespace(
$contents,
[
'namespace' => $namespace,
'package' => $package['package'],
'strict' => true,
]
);
}
}
}
/**
* Prefix any import statements and direct uses of namespace.
*
* @since 2.3.9
*
* @param string $contents File contents.
* @param array $package Package prefix configuration.
*/
function prefix_uses( &$contents, $package ) {
global $namespace_prefix;
$quoted = preg_quote( $package['namespace'], '#' );
// Match only the full namespace when strict is enabled.
if ( $package['strict'] ) {
$regex = "#^(\s*)(use)\s*({$quoted}\\\\[a-zA-Z0-9_]+[;| ])#m";
} else {
$regex = "#^(\s*)(use)\s*({$quoted}\\\\)#m";
}
$contents = preg_replace(
$regex,
"\$1\$2 {$namespace_prefix}\\\\\$3",
$contents
);
// Replace direct class extends.
$contents = preg_replace(
"#(\s*)([class|interface] .* extends)\s*(\\\\{$quoted}\\\\[a-zA-Z0-9_]+\s*\{?)$#m",
"\$1\$2 \\\\{$namespace_prefix}\$3",
$contents
);
// Replace direct class implements.
$contents = preg_replace(
"#(\s*)(class .* implements)\s*([a-zA-Z0-9_\\,]*\s*)(\\\\{$quoted}\\\\[a-zA-Z0-9_]+\s*\{?)$#m",
"\$1\$2 \$3\\\\{$namespace_prefix}\$4",
$contents
);
if ( $package['strict'] && ! empty( $package['extra_namespaces'] ) ) {
foreach ( $package['extra_namespaces'] as $namespace ) {
prefix_uses(
$contents,
[
'namespace' => $namespace,
'package' => $package['package'],
'strict' => true,
]
);
}
}
}
/**
* Prefix any direct string.
*
* @since 2.3.9
*
* @param string $contents File contents.
* @param string $search String to search for.
*/
function prefix_string( &$contents, $search ) {
global $namespace_prefix;
$quoted = preg_quote( $search, '#' );
$namespace_quoted = preg_quote( $namespace_prefix . '\\', '#' );
$contents = preg_replace(
"#((?<!{$namespace_quoted}){$quoted})#m", // prevent to add the namespace twice
"{$namespace_prefix}\\\\\$1",
$contents
);
}
/**
* Find a list of files in a path matching a pattern.
*
* @since 2.2.2
*
* @param string $path Package path
* @param string $pattern Regex pattern to match
* @return array Matching files
*/
function get_dir_contents( $path, $pattern ) {
try {
$rdi = new RecursiveDirectoryIterator( $path );
} catch ( UnexpectedValueException $e ) {
printf(
'Expected directory "%s" was not found' . PHP_EOL,
$path
);
exit( 1 );
}
$rii = new RecursiveIteratorIterator( $rdi );
$rri = new RegexIterator( $rii, $pattern );
$files = [];
foreach ( $rri as $file ) {
$files[] = $file->getPathname();
}
return $files;
}
/**
* Find a list of PHP files for this package.
*
* @since 1.1.0
*
* @param string $package Package name.
* @return array List of files.
*/
function find_files( string $package ): array {
global $vendor_dir;
return get_dir_contents( "{$vendor_dir}/{$package}", '/\.php$/i' );
}
/**
* Find a list of dependent PHP files for this package.
*
* @since 2.3.9
*
* @param string $package Package name.
* @return array Merged list of files.
*/
function find_dependent_files( string $package ): array {
global $vendor_dir, $dependencies;
if ( empty( $dependencies[ $package ] ) ) {
return [];
}
$files = [];
foreach ( $dependencies[ $package ] as $dependency ) {
$dependent_files = get_dir_contents( "{$vendor_dir}/{$dependency}", '/\.php$/i' );
$files = array_merge( $files, $dependent_files );
}
return $files;
}
/**
* Removes any autoload files from a package, and confirms they are loaded from the main composer.json file.
* This ensures that the generated file vendor/composer/autoload_files.php will only autoload the files once,
* using the new namespace. Autoloading the files from our main composer.json ensures we use a unique hash so
* we don't conflict with other extensions autoloading the same files.
*
* The second task of this function is to prefix any autoloads with our custom namespace prefix.
*
* @since 2.3.9
*
* @param string $file Generated file containing information about all the installed packages
* @param array $composer_autoload List of autoloaded files in composer.json
* @param array $package Package prefix configuration.
*/
function update_autoloads( string $file, array $composer_autoload, array $package ) {
global $namespace_prefix;
if ( ! file_exists( $file ) ) {
return;
}
$json = json_decode( file_get_contents( $file ), true );
if ( empty( $json['packages'] ) ) {
return;
}
$modified = false;
foreach ( $json['packages'] as $key => $dep_package ) {
// If strict confirm that full package name matches.
if ( $package['strict'] && $dep_package['name'] !== $package['package'] ) {
continue;
}
// Check if start of package name matches.
if ( 0 !== stripos( $dep_package['name'], $package['package'] ) ) {
continue;
}
if ( empty( $dep_package['autoload'] ) ) {
continue;
}
// Remove any file autoloads and ensure they are included in the main composer file
if ( ! empty( $dep_package['autoload']['files'] ) ) {
$modified = true;
foreach ( $dep_package['autoload']['files'] as $autoload_file ) {
// Confirm we already include this autoload in the main composer file.
$filename = "vendor/{$dep_package['name']}/{$autoload_file}";
if ( in_array( $filename, $composer_autoload, true ) ) {
continue;
}
// Confirm this file isn't being excluded.
if ( in_array( $autoload_file, $package['exclude_autoload'], true ) ) {
continue;
}
printf(
'Autoloaded file "%s" should be included in composer.json' . PHP_EOL,
$filename
);
exit( 1 );
}
$json['packages'][ $key ]['autoload']['files'] = [];
}
// Prefix any of the autoloads for this specific package.
foreach ( $json['packages'][ $key ]['autoload'] as $type => $mappings ) {
foreach ( $mappings as $namespace => $path ) {
if ( 0 === stripos( (string) $namespace, $package['namespace'] ) ) {
$modified = true;
unset( $json['packages'][ $key ]['autoload'][ $type ][ $namespace ] );
$json['packages'][ $key ]['autoload'][ $type ][ "{$namespace_prefix}\\{$namespace}" ] = $path;
}
}
}
}
if ( $modified ) {
file_put_contents(
$file,
json_encode( $json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE )
);
}
}