-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.php
100 lines (89 loc) · 2.43 KB
/
command.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
<?php
namespace BEAPI\Clear_Opcache;
/**
*
* Class Clear_Opcache
* @package BEAPI\Clear_Opcache
*
* @author Léonard Phoumpakka
*
*/
class Clear_Opcache {
private $secret;
public function __construct() {
$this->secret = RESET_OPCACHE_SECRET;
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
add_action( 'plugins_loaded', [ $this, 'clear_opcache' ] );
}
if ( defined( 'WP_CLI' ) ) {
\WP_CLI::add_command( 'clear-opcache', [ $this, 'clear_command'], 10, 2 );
}
}
/**
* Reset opcache when a request is received with a specific key
*
* @author Ingrid Azéma
*/
public function clear_opcache(): void {
if ( isset( $_GET['secret'] ) && $this->secret === $_GET['secret'] ) {
if ( opcache_reset() ) {
status_header( 202 );
} else {
status_header( 400 );
}
die;
}
}
/**
* Command to clear opcache on 1 or several servers
*
* ## OPTIONS
* [--host=<host>]
* : Hostname (staging.mydomain.com). Required
*
* [--servers=<servers>]
* : List of server names on which opcache must be reset (srv-www-1, srv-www-2). Required
*
* ## EXAMPLES
*
* wp clear-opcache --url=https://staging.mydomain.com --host=staging.mydomain.com --servers=srv-www-1,srv-www-2
*
* @author Ingrid Azéma
*/
public function clear_command( $args, $assoc_args ): void {
// Constant to be defined as env var
if ( empty( $this->secret ) ) {
\WP_CLI::error( 'Please define a constant named RESET_OPCACHE_SECRET with a string of your choosing' );
}
if ( empty( $assoc_args ) || ( empty( $assoc_args['host'] ) && empty( $assoc_args['servers'] ) ) ) {
\WP_CLI::error( 'Please provide a host name (ex. --host=staging.mydomain.com) and at least 1 server-name (ex. --servers=srv-www-1,srv-www-2)' );
}
$servers = explode( ',', $assoc_args['servers'] ) ;
foreach ( $servers as $server_name ) {
$url = add_query_arg(
[
'secret' => $this->secret,
],
'http://' . $server_name
);
$response = wp_remote_get(
$url,
[
'headers' => [
'Host' => $assoc_args['host'],
]
]
);
if ( is_wp_error( $response) ) {
\WP_CLI::error( sprintf( 'Failed to send clear request to %s', $server_name ), false );
continue;
}
$response_code = wp_remote_retrieve_response_code( $response );
if ( 202 === $response_code ) {
\WP_CLI::log( 'Opcache cleared on ' . $server_name );
continue;
}
\WP_CLI::log( 'Failed to clear opcache on ' . $server_name );
}
}
}