-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtils.php
More file actions
720 lines (617 loc) · 21.3 KB
/
Copy pathUtils.php
File metadata and controls
720 lines (617 loc) · 21.3 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
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
<?php
/**
* This file contains the Utils class
*
* @package Mantle
*/
namespace Mantle\Testing;
use Mantle\Support\Collection;
use Mantle\Support\Str;
use Mantle\Testing\Doubles\Spy_REST_Server;
use function Mantle\Support\Helpers\capture;
use function Mantle\Support\Helpers\collect;
use function Termwind\render;
require_once __DIR__ . '/Concerns/Output_Messages.php';
/**
* Assorted testing utilities.
*
* A fork of https://github.com/WordPress/wordpress-develop/blob/master/tests/phpunit/includes/utils.php.
*/
class Utils {
use Concerns\Output_Messages;
/**
* Default database name.
*
* @var string
*/
public const DEFAULT_DB_NAME = 'wordpress_unit_tests';
/**
* Default database user.
*
* @var string
*/
public const DEFAULT_DB_USER = 'root';
/**
* Default database password.
*
* @var string
*/
public const DEFAULT_DB_PASSWORD = 'root';
/**
* Default database host.
*
* @var string
*/
public const DEFAULT_DB_HOST = 'localhost';
/**
* Default permalink structure.
*
* @var string
*/
public const DEFAULT_PERMALINK_STRUCTURE = '/%year%/%monthnum%/%day%/%postname%/';
/**
* Get the current working directory or throw an exception.
*
* @throws \RuntimeException If the current working directory cannot be determined.
* @return string The current working directory.
*/
public static function cwd(): string {
$cwd = getcwd();
if ( ! $cwd ) {
throw new \RuntimeException( 'Could not get current working directory.' );
}
return $cwd;
}
/**
* Get the output from a given callable.
*
* @deprecated Use \Mantle\Support\Helpers::capture() instead.
*
* @param callable $callable Callable to execute.
* @param array $args Arguments to pass to the callable.
* @return string Rendered output.
*/
public static function get_echo( callable $callable, array $args = [] ): string {
return capture( fn () => $callable( ...$args ) );
}
/**
* Unregister a post status.
*
* @param string $status Post status to unregister.
*/
public static function unregister_post_status( string $status ): void {
unset( $GLOBALS['wp_post_statuses'][ $status ] );
}
/**
* Remove WP query vars from the global space.
*/
public static function cleanup_query_vars(): void {
// Clean out globals to stop them polluting wp and wp_query.
foreach ( $GLOBALS['wp']->public_query_vars as $v ) {
unset( $GLOBALS[ $v ] );
}
foreach ( $GLOBALS['wp']->private_query_vars as $v ) {
unset( $GLOBALS[ $v ] );
}
foreach ( get_taxonomies( [], 'objects' ) as $t ) {
if ( $t->publicly_queryable && ! empty( $t->query_var ) ) {
$GLOBALS['wp']->add_query_var( $t->query_var );
}
}
foreach ( get_post_types( [], 'objects' ) as $t ) {
if ( is_post_type_viewable( $t ) && ! empty( $t->query_var ) ) {
$GLOBALS['wp']->add_query_var( $t->query_var );
}
}
}
/**
* Reset `$_SERVER` variables
*/
public static function reset_server(): void {
$_SERVER['HTTP_HOST'] = WP_TESTS_DOMAIN;
$_SERVER['REMOTE_ADDR'] = '127.0.0.1'; // phpcs:ignore WordPressVIPMinimum.Variables
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REQUEST_URI'] = '';
$_SERVER['SERVER_NAME'] = WP_TESTS_DOMAIN;
$_SERVER['SERVER_PORT'] = '80';
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
unset( $_SERVER['HTTP_REFERER'] );
if ( defined( 'WP_TESTS_USE_HTTPS' ) && WP_TESTS_USE_HTTPS ) {
$_SERVER['HTTPS'] = 'on';
$_SERVER['SERVER_PORT'] = '443';
} else {
unset( $_SERVER['HTTPS'] );
}
}
/**
* Use the Spy_REST_Server class for the REST server.
*
* @return string The server class name.
*/
public static function wp_rest_server_class_filter(): string {
return Spy_REST_Server::class;
}
/**
* Deletes all data from the database and flushes the cache.
*/
public static function delete_all_data(): void {
// phpcs:disable WordPress.DB,WordPressVIPMinimum.Variables
global $wpdb;
foreach ( [
$wpdb->posts,
$wpdb->postmeta,
$wpdb->comments,
$wpdb->commentmeta,
$wpdb->term_relationships,
$wpdb->termmeta,
] as $table ) {
$wpdb->query( "DELETE FROM {$table}" );
}
foreach ( [
$wpdb->terms,
$wpdb->term_taxonomy,
] as $table ) {
$wpdb->query( "DELETE FROM {$table} WHERE term_id != 1" );
}
$wpdb->query( "UPDATE {$wpdb->term_taxonomy} SET count = 0" );
$wpdb->query( "DELETE FROM {$wpdb->users} WHERE ID != 1" );
$wpdb->query( "DELETE FROM {$wpdb->usermeta} WHERE user_id != 1" );
// phpcs:enable
self::flush_cache();
}
/**
* Delete all other blogs from the database.
*
* Ensures that the main blog (blog_id = 1) is not deleted.
*
* @throws \RuntimeException If not in multisite mode.
*/
public static function delete_all_blogs(): void {
if ( ! is_multisite() ) {
throw new \RuntimeException( 'Cannot delete all blogs when not in multisite mode.' );
}
// phpcs:disable WordPress.DB,WordPressVIPMinimum.Variables
global $wpdb;
if ( ! function_exists( 'wpmu_delete_blog' ) ) {
require_once ABSPATH . 'wp-admin/includes/ms.php';
}
foreach ( $wpdb->get_col( "SELECT blog_id FROM {$wpdb->blogs} WHERE blog_id != 1" ) as $blog_id ) {
wpmu_delete_blog( $blog_id, true );
}
// phpcs:enable
self::flush_cache();
}
/**
* Deletes all posts from the database.
*/
public static function delete_all_posts(): void {
global $wpdb;
// phpcs:ignore WordPress.DB
$all_posts = $wpdb->get_results( "SELECT ID, post_type from {$wpdb->posts}", ARRAY_A );
if ( ! $all_posts ) {
return;
}
foreach ( $all_posts as $all_post ) {
if ( 'attachment' === $all_post['post_type'] ) {
wp_delete_attachment( $all_post['ID'], true );
} else {
wp_delete_post( $all_post['ID'], true );
}
}
}
/**
* Flushes the WordPress object cache.
*/
public static function flush_cache(): void {
wp_cache_flush_runtime();
global $wp_object_cache;
if ( is_object( $wp_object_cache ) && method_exists( $wp_object_cache, '__remoteset' ) ) {
$wp_object_cache->__remoteset();
}
wp_cache_flush();
wp_cache_add_global_groups(
[
'blog-details',
'blog-id-cache',
'blog-lookup',
'blog_meta',
'global-posts',
'networks',
'network-queries',
'sites',
'site-details',
'site-options',
'site-queries',
'site-transient',
'theme_files',
'rss',
'users',
'user-queries',
'user_meta',
'useremail',
'userlogins',
'userslugs',
]
);
wp_cache_add_non_persistent_groups( [ 'counts', 'plugins', 'theme_json' ] );
}
/**
* Retrieve all of core's conditional tags from WP_Query.
*
* This should return a list of all conditional tags (is_<name>) that are
* currently provided by WordPress. Core can always add new conditional tags
* in the future and we don't want to maintain a hardcoded list.
*
* @return callable-string[]
*/
public static function get_query_conditional_tags(): array {
return collect( get_class_methods( \WP_Query::class ) ) // @phpstan-ignore-line
->filter( fn ( $method ) => str_starts_with( $method, 'is_' ) && function_exists( $method ) )
->reject( fn ( $method ) => in_array( $method, [ 'is_comments_popup', 'is_main_query' ], true ) )
->sort()
->values()
->all();
}
/**
* Set a permalink structure.
*
* Hooked as a callback to the 'populate_options' action, we use this function to set a permalink structure during
* `wp_install()`, so that WP doesn't attempt to do a time-consuming remote request.
*
* @since 4.2.0
*/
public static function set_default_permalink_structure_for_tests(): void {
update_option( 'permalink_structure', static::DEFAULT_PERMALINK_STRUCTURE );
}
/**
* Define the constants that are necessary for WordPress installation.
*
* Mirrors the wp-tests-config-sample.php file that can optionally be loaded
* before this file. Any constant that is already defined is not overridden
* with the option to use environment variables to override the default
* values.
*/
public static function setup_configuration(): void {
global $table_prefix;
$dir = defined( 'WP_TESTS_INSTALL_PATH' ) ? WP_TESTS_INSTALL_PATH : __DIR__;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound
defined( 'ABSPATH' ) || define( 'ABSPATH', Str::trailing_slash( (string) preg_replace( '#/' . preg_quote( static::content_directory_name(), '#' ) . '/.*$#', '/', (string) $dir ) ) );
defined( 'WP_DEBUG' ) || define( 'WP_DEBUG', true );
defined( 'DB_NAME' ) || define( 'DB_NAME', static::env( 'WP_DB_NAME', static::DEFAULT_DB_NAME ) );
defined( 'DB_USER' ) || define( 'DB_USER', static::env( 'WP_DB_USER', static::DEFAULT_DB_USER ) );
defined( 'DB_PASSWORD' ) || define( 'DB_PASSWORD', static::env( 'WP_DB_PASSWORD', static::DEFAULT_DB_PASSWORD ) );
defined( 'DB_HOST' ) || define( 'DB_HOST', static::env( 'WP_DB_HOST', static::DEFAULT_DB_HOST ) );
defined( 'DB_CHARSET' ) || define( 'DB_CHARSET', static::ENV( 'WP_DB_CHARSET', 'utf8' ) );
defined( 'DB_COLLATE' ) || define( 'DB_COLLATE', static::ENV( 'WP_DB_COLLATE', '' ) );
defined( 'AUTH_KEY' ) || define( 'AUTH_KEY', 'put your unique phrase here' );
defined( 'SECURE_AUTH_KEY' ) || define( 'SECURE_AUTH_KEY', 'put your unique phrase here' );
defined( 'LOGGED_IN_KEY' ) || define( 'LOGGED_IN_KEY', 'put your unique phrase here' );
defined( 'NONCE_KEY' ) || define( 'NONCE_KEY', 'put your unique phrase here' );
defined( 'AUTH_SALT' ) || define( 'AUTH_SALT', 'put your unique phrase here' );
defined( 'SECURE_AUTH_SALT' ) || define( 'SECURE_AUTH_SALT', 'put your unique phrase here' );
defined( 'LOGGED_IN_SALT' ) || define( 'LOGGED_IN_SALT', 'put your unique phrase here' );
defined( 'NONCE_SALT' ) || define( 'NONCE_SALT', 'put your unique phrase here' );
$table_prefix = 'wptests_'; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
defined( 'WP_TESTS_DOMAIN' ) || define( 'WP_TESTS_DOMAIN', static::env( 'WP_TESTS_DOMAIN', 'example.org' ) );
defined( 'WP_TESTS_USE_HTTPS' ) || define( 'WP_TESTS_USE_HTTPS', static::env_bool( 'WP_TESTS_USE_HTTPS', false ) );
defined( 'WP_TESTS_EMAIL' ) || define( 'WP_TESTS_EMAIL', 'admin@example.org' );
defined( 'WP_TESTS_TITLE' ) || define( 'WP_TESTS_TITLE', 'Test Site' );
defined( 'WP_PHP_BINARY' ) || define( 'WP_PHP_BINARY', 'php' );
defined( 'WPLANG' ) || define( 'WPLANG', '' );
// Setup the table prefix when running in parallel.
if ( static::is_parallel() && $token = static::parallel_token() ) {
$table_prefix .= "para_{$token}_"; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
if ( static::is_debug_mode() ) {
static::info( "Using parallel table prefix: {$table_prefix}" );
}
}
// phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound
}
/**
* Retrieve an environment variable with a fallback.
*
* @param string $variable Variable to get.
* @param mixed $default Default value.
*/
public static function env( string $variable, mixed $default ): mixed {
$value = getenv( $variable );
return false === $value ? $default : $value;
}
/**
* Retrieve the name of the wp-content directory.
*
* Defaults to `wp-content` but can be overridden via the `WP_CONTENT_DIR_NAME`
* environment variable to support alternative layouts such as Bedrock (`app`)
* or any other custom `WP_CONTENT_DIR`. Mantle uses this name to detect whether
* the codebase already lives inside a WordPress installation and to resolve the
* installation root. Setting it to a value that does not appear in the project
* path forces Mantle to treat the codebase as standalone and install an
* isolated WordPress.
*/
public static function content_directory_name(): string {
return trim( (string) static::env( 'WP_CONTENT_DIR_NAME', 'wp-content' ), '/' );
}
/**
* Retrieve an environment variable and check if it is truthy.
*
* @param string $variable Variable to get.
* @param bool $default Default value used as a fallback.
*/
public static function env_bool( string $variable, bool $default ): bool {
$value = static::env( $variable, $default );
return in_array( strtolower( (string) $value ), [ 'true', '1', 'yes' ], true );
}
/**
* Ensure an environment variable is is a valid string that can be passed to
* to a shell script.
*
* For example, an empty string should be '' vs a blank space.
* `escapeshellarg()` doesn't fit here because the script is expecting
* unquoted arguments.
*
* @param string|bool $string String to sanitize.
*/
public static function shell_safe( string|bool $string ): string {
if ( is_bool( $string ) ) {
return $string ? 'true' : 'false';
}
return empty( trim( $string ) ) ? "''" : "\"{$string}\"";
}
/**
* Install a WordPress codebase through a shell script.
*
* This installs the WordPress codebase in the specified directory. It does
* not install the WordPress database.
*
* @param string $directory Directory to install WordPress in.
*/
public static function install_wordpress( string $directory ): void {
$install_vip_mu_plugins = static::env_bool( 'MANTLE_INSTALL_VIP_MU_PLUGINS', false );
$use_sqlite_db = static::env_bool( 'MANTLE_USE_SQLITE', false );
// Handle the legacy values for MANTLE_INSTALL_OBJECT_CACHE.
if ( static::env_bool( 'MANTLE_INSTALL_OBJECT_CACHE', false ) ) {
$install_object_cache = 'memcached';
} else {
$install_object_cache = static::env( 'MANTLE_INSTALL_OBJECT_CACHE', false );
if ( $install_object_cache && ! in_array( $install_object_cache, [ 'memcached', 'redis' ], true ) ) {
static::error( '🚨 Invalid value for MANTLE_INSTALL_OBJECT_CACHE (' . $install_object_cache . '). Ignoring...' );
$install_object_cache = false;
}
}
$branch = static::env( 'MANTLE_CI_BRANCH', 'HEAD' );
if ( ! self::env( 'WP_CORE_DIR', false ) ) {
putenv( "WP_CORE_DIR={$directory}" ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions
}
// Compile the variables to pass to the shell script.
$variables = collect(
[
[ 'WP_CORE_DIR', $directory ],
[ 'WP_MULTISITE', static::env( 'WP_MULTISITE', '0' ) ],
]
)
->when(
$use_sqlite_db,
fn ( Collection $collection ) => $collection->push( [ 'WP_USE_SQLITE', 'true' ] )
)
->when(
static::is_debug_mode(),
fn ( Collection $collection ) => $collection->push( [ 'INSTALL_WP_TEST_DEBUG', 'true' ] )
)
->when(
! empty( static::env( 'CACHEDIR', '' ) ),
fn ( Collection $collection ) => $collection->push( [ 'CACHEDIR', static::env( 'CACHEDIR', '' ) ] )
)
->map(
fn ( array $item ) => sprintf( 'export %s=%s', $item[0], static::shell_safe( $item[1] ) )
)
->implode( ' && ' );
$command = sprintf(
'%s && curl -s %s | bash -s %s',
$variables,
"https://raw.githubusercontent.com/alleyinteractive/mantle-ci/{$branch}/install-wp-tests.sh",
collect(
[
static::shell_safe( defined( 'DB_NAME' ) ? DB_NAME : static::env( 'WP_DB_NAME', static::DEFAULT_DB_NAME ) ),
static::shell_safe( defined( 'DB_USER' ) ? DB_USER : static::env( 'WP_DB_USER', static::DEFAULT_DB_USER ) ),
static::shell_safe( defined( 'DB_PASSWORD' ) ? DB_PASSWORD : static::env( 'WP_DB_PASSWORD', static::DEFAULT_DB_PASSWORD ) ),
static::shell_safe( defined( 'DB_HOST' ) ? DB_HOST : static::env( 'WP_DB_HOST', static::DEFAULT_DB_HOST ) ),
static::shell_safe( static::env( 'WP_VERSION', 'latest' ) ),
static::shell_safe( static::env( 'WP_SKIP_DB_CREATE', 'false' ) ),
static::shell_safe( $install_vip_mu_plugins ? 'true' : 'false' ),
static::shell_safe( $install_object_cache ), // @phpstan-ignore-line argument.type
]
)->implode( ' ' ),
);
$retval = 0;
$output = static::command( $command, $retval );
if ( 0 !== $retval ) {
static::error( '🚨 Error installing WordPress! Output from installation:', 'Install Rsync' );
static::code( $output );
exit( 1 );
}
}
/**
* Install a plugin to a WordPress codebase through a shell script.
*
* @param string $directory Directory to install WordPress in.
* @param string $plugin Plugin slug to install.
* @param string $version_or_url Plugin version to install OR URL to install from.
*/
public static function install_plugin( string $directory, string $plugin, string $version_or_url = 'latest' ): void {
$branch = static::env( 'MANTLE_CI_BRANCH', 'HEAD' );
// Compile the variables to pass to the shell script.
$variables = collect(
[
[ 'WP_CORE_DIR', $directory ],
]
)
->when(
! empty( static::env( 'CACHEDIR', '' ) ),
fn ( Collection $collection ) => $collection->push( [ 'CACHEDIR', static::env( 'CACHEDIR', '' ) ] )
)
->map(
fn ( array $item ) => sprintf( 'export %s=%s', $item[0], static::shell_safe( $item[1] ) )
)
->implode( ' && ' );
$command = sprintf(
'%s && curl -s %s | bash -s %s',
$variables,
"https://raw.githubusercontent.com/alleyinteractive/mantle-ci/{$branch}/install-plugin.sh",
collect(
[
$plugin,
$version_or_url,
]
)->implode( ' ' ),
);
$retval = 0;
$output = static::command( $command, $retval );
if ( 0 !== $retval ) {
static::error( '🚨 Error installing WordPress! Output from installation:', 'Install Rsync' );
static::code( $output );
exit( 1 );
}
}
/**
* Check if the command is being run in debug mode.
*/
public static function is_debug_mode(): bool {
if ( defined( 'MANTLE_TESTING_DEBUG' ) && MANTLE_TESTING_DEBUG ) {
return true;
}
if ( self::env_bool( 'MANTLE_TESTING_DEBUG', false ) ) {
return true;
}
return ! empty(
array_intersect(
(array) ( $_SERVER['argv'] ?? [] ), // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
[
'--debug',
'--verbose',
'-v',
],
)
);
}
/**
* Output a debug message if in debug mode.
*
* @param string $message Message to output.
* @param string $prefix Optional prefix for the message.
*/
public static function debug( string $message, string $prefix = 'Install' ): void {
if ( static::is_debug_mode() ) {
static::info( $message, $prefix );
}
}
/**
* Check if we're running in a CI (Continuous Integration) environment.
*/
public static function is_ci(): bool {
return (
! empty( $_SERVER['GITHUB_ENV'] )
|| ( ! empty( $_SERVER['CI'] ) && in_array( $_SERVER['CI'], [ 'true', '1' ], true ) )
|| ! empty( $_SERVER['GITHUB_REPOSITORY_OWNER'] )
|| ! empty( $_SERVER['GITHUB_WORKFLOW'] )
|| ! empty( $_SERVER['GITHUB_EVENT_NAME'] )
);
}
/**
* Run a system command and return the output.
*
* @param string|string[] $command Command to run.
* @param int|null $exit_code Exit code.
* @param-out int $exit_code Exit code.
* @return string[]
*/
public static function command( string|array $command, &$exit_code = null ): array {
$is_debug_mode = static::is_debug_mode();
// Display the command if in debug mode.
if ( $is_debug_mode ) {
$time = microtime( true );
render(
'<div class="p-1">
Running:
<code>' . implode( ' ', (array) $command ) . '</code>
</div>'
);
}
if ( is_array( $command ) ) {
$command = implode( ' ', $command );
}
$output = null;
exec( $command, $output, $exit_code ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.system_calls_exec
// Display the command runtime if in debug mode.
if ( $is_debug_mode ) {
$time = microtime( true ) - $time;
render(
'<div class="p-1">
Finished in ' . number_format( $time, 2 ) . 's with exit code ' . $exit_code . '.
</div>'
);
}
return $output;
}
/**
* Ensure that Composer is loaded for the current environment.
*/
public static function ensure_composer_loaded(): void {
$paths = [
preg_replace( '#/vendor/.*$#', '/vendor/autoload.php', __DIR__ ),
__DIR__ . '/../../../vendor/autoload.php',
__DIR__ . '/../../vendor/autoload.php',
];
foreach ( $paths as $path ) {
if ( $path && ! is_dir( $path ) && file_exists( $path ) ) {
require_once $path; // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable
return;
}
}
}
/**
* Register a shutdown function to handle errors.
*
* Used during the WordPress installation process to catch silent errors.
*/
public static function register_shutdown_function(): void {
register_shutdown_function( [ static::class, 'handle_shutdown' ] );
}
/**
* Handle a shutdown error and display it.
*/
public static function handle_shutdown(): void {
$error = error_get_last();
if ( ! $error ) {
return;
}
// Ignore deprecated errors.
if ( E_DEPRECATED === $error['type'] || E_USER_DEPRECATED === $error['type'] ) {
return;
}
static::error( '🚨 Error during test run:', 'Shutdown' );
static::code( $error ); // @phpstan-ignore-line argument.type
exit( 1 );
}
/**
* Check if the current test run is parallel with paratest.
*/
public static function is_parallel(): bool {
return ! empty( static::parallel_token() );
}
/**
* Retrieve the parallel token for the current test run.
*
* @return string
*/
public static function parallel_token(): ?string {
return static::env( 'TEST_TOKEN', null );
}
/**
* Check if the current test run is the paratest bootstrap.
*
* The parallel token will not be set in the initial bootstrap.
*/
public static function is_parallel_bootstrap(): bool {
return empty( static::parallel_token() ) && isset( $_SERVER['SCRIPT_NAME'] ) && str_contains( (string) $_SERVER['SCRIPT_NAME'], 'paratest' ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
}
}