Repository navigation
Expand file tree
/
Copy pathWPConfigTransformer.php
More file actions
378 lines (324 loc) · 11.4 KB
/
Copy pathWPConfigTransformer.php
File metadata and controls
378 lines (324 loc) · 11.4 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
<?php
/**
* Transforms a wp-config.php file.
*/
class WPConfigTransformer {
/**
* Append to end of file
*/
const ANCHOR_EOF = 'EOF';
/**
* Path to the wp-config.php file.
*
* @var string
*/
protected $wp_config_path;
/**
* Original source of the wp-config.php file.
*
* @var string
*/
protected $wp_config_src;
/**
* Array of parsed configs.
*
* @var array<string, array<string, array{src: string, value: string, parts: array<string>}>>
*/
protected $wp_configs = array();
/**
* Instantiates the class with a valid wp-config.php.
*
* @throws Exception If the wp-config.php file is missing.
* @throws Exception If the wp-config.php file is not writable.
*
* @param string $wp_config_path Path to a wp-config.php file.
*/
public function __construct( $wp_config_path, $read_only = false ) {
$basename = basename( $wp_config_path );
if ( ! file_exists( $wp_config_path ) ) {
throw new Exception( "{$basename} does not exist." );
}
if ( ! $read_only && ! is_writable( $wp_config_path ) ) {
throw new Exception( "{$basename} is not writable." );
}
$this->wp_config_path = $wp_config_path;
}
/**
* Checks if a config exists in the wp-config.php file.
*
* @throws Exception If the wp-config.php file is empty.
* @throws Exception If the requested config type is invalid.
*
* @param string $type Config type (constant or variable).
* @param string $name Config name.
*
* @return bool
*/
public function exists( $type, $name ) {
$wp_config_src = (string) file_get_contents( $this->wp_config_path );
if ( ! trim( $wp_config_src ) ) {
throw new Exception( 'Config file is empty.' );
}
// Normalize the newline to prevent an issue coming from OSX.
$this->wp_config_src = str_replace( array( "\r\n", "\n\r", "\r" ), "\n", $wp_config_src );
$this->wp_configs = $this->parse_wp_config( $this->wp_config_src );
if ( ! isset( $this->wp_configs[ $type ] ) ) {
throw new Exception( "Config type '{$type}' does not exist." );
}
return isset( $this->wp_configs[ $type ][ $name ] );
}
/**
* Get the value of a config in the wp-config.php file.
*
* @throws Exception If the wp-config.php file is empty.
* @throws Exception If the requested config type is invalid.
*
* @param string $type Config type (constant or variable).
* @param string $name Config name.
*
* @return string|null
*/
public function get_value( $type, $name ) {
$wp_config_src = (string) file_get_contents( $this->wp_config_path );
if ( ! trim( $wp_config_src ) ) {
throw new Exception( 'Config file is empty.' );
}
$this->wp_config_src = $wp_config_src;
$this->wp_configs = $this->parse_wp_config( $this->wp_config_src );
if ( ! isset( $this->wp_configs[ $type ] ) ) {
throw new Exception( "Config type '{$type}' does not exist." );
}
return $this->wp_configs[ $type ][ $name ]['value'];
}
/**
* Adds a config to the wp-config.php file.
*
* @throws Exception If the config value provided is not a string.
* @throws Exception If the config placement anchor could not be located.
*
* @param string $type Config type (constant or variable).
* @param string $name Config name.
* @param string $value Config value.
* @param array<string, bool|string> $options (optional) Array of special behavior options.
*
* @return bool
*/
public function add( $type, $name, $value, array $options = array() ) {
if ( ! is_string( $value ) ) {
throw new Exception( 'Config value must be a string.' );
}
if ( $this->exists( $type, $name ) ) {
return false;
}
$defaults = array(
'raw' => false, // Display value in raw format without quotes.
'anchor' => "/* That's all, stop editing!", // Config placement anchor string.
'separator' => PHP_EOL, // Separator between config definition and anchor string.
'placement' => 'before', // Config placement direction (insert before or after).
);
list( $raw, $anchor, $separator, $placement ) = array_values( array_merge( $defaults, $options ) );
$raw = (bool) $raw;
$anchor = (string) $anchor;
$separator = (string) $separator;
$placement = (string) $placement;
if ( self::ANCHOR_EOF === $anchor ) {
$contents = $this->wp_config_src . $this->normalize( $type, $name, $this->format_value( $value, $raw ) );
} else {
if ( false === strpos( $this->wp_config_src, $anchor ) ) {
throw new Exception( 'Unable to locate placement anchor.' );
}
$new_src = $this->normalize( $type, $name, $this->format_value( $value, $raw ) );
$new_src = ( 'after' === $placement ) ? $anchor . $separator . $new_src : $new_src . $separator . $anchor;
$contents = str_replace( $anchor, $new_src, $this->wp_config_src );
}
return $this->save( $contents );
}
/**
* Updates an existing config in the wp-config.php file.
*
* @throws Exception If the config value provided is not a string.
*
* @param string $type Config type (constant or variable).
* @param string $name Config name.
* @param string $value Config value.
* @param array<string, bool> $options (optional) Array of special behavior options.
*
* @return bool
*/
public function update( $type, $name, $value, array $options = array() ) {
if ( ! is_string( $value ) ) {
throw new Exception( 'Config value must be a string.' );
}
$defaults = array(
'add' => true, // Add the config if missing.
'raw' => false, // Display value in raw format without quotes.
'normalize' => false, // Normalize config output using WP Coding Standards.
);
list( $add, $raw, $normalize ) = array_values( array_merge( $defaults, $options ) );
$add = (bool) $add;
$raw = (bool) $raw;
$normalize = (bool) $normalize;
if ( ! $this->exists( $type, $name ) ) {
return ( $add ) ? $this->add( $type, $name, $value, $options ) : false;
}
$old_src = $this->wp_configs[ $type ][ $name ]['src'];
$old_value = $this->wp_configs[ $type ][ $name ]['value'];
/**
* @var string $new_value
*/
$new_value = $this->format_value( $value, $raw );
if ( $normalize ) {
$new_src = $this->normalize( $type, $name, $new_value );
} else {
$new_parts = $this->wp_configs[ $type ][ $name ]['parts'];
$new_parts[1] = str_replace( $old_value, $new_value, $new_parts[1] ); // Only edit the value part.
$new_src = implode( '', $new_parts );
}
$contents = (string) preg_replace(
sprintf( '/(?<=^|;|<\?php\s|<\?\s)(\s*?)%s/m', preg_quote( trim( $old_src ), '/' ) ),
'$1' . str_replace( '$', '\$', trim( $new_src ) ),
$this->wp_config_src
);
return $this->save( $contents );
}
/**
* Removes a config from the wp-config.php file.
*
* @param string $type Config type (constant or variable).
* @param string $name Config name.
*
* @return bool
*/
public function remove( $type, $name ) {
if ( ! $this->exists( $type, $name ) ) {
return false;
}
if ( 'constant' === $type ) {
$pattern = sprintf(
"/\bdefine\s*\(\s*['\"]%s['\"]\s*,\s*(('[^']*'|\"[^\"]*\")|\s*(?:[\s\S]*?))\s*\)\s*;\s*/mi",
preg_quote( $name, '/' )
);
} else {
$pattern = sprintf(
'/^\s*\$%s\s*=\s*[\s\S]*?;\s*$/mi',
preg_quote( $name, '/' )
);
}
$contents = (string) preg_replace( $pattern, '', $this->wp_config_src );
return $this->save( $contents );
}
/**
* Applies formatting to a config value.
*
* @throws Exception When a raw value is requested for an empty string.
*
* @param string $value Config value.
* @param bool $raw Display value in raw format without quotes.
*
* @return bool|float|int|string|null
*/
protected function format_value( $value, $raw ) {
if ( $raw && '' === trim( $value ) ) {
throw new Exception( 'Raw value for empty string not supported.' );
}
return ( $raw ) ? $value : var_export( $value, true );
}
/**
* Normalizes the source output for a name/value pair.
*
* @throws Exception If the requested config type does not support normalization.
*
* @param string $type Config type (constant or variable).
* @param string $name Config name.
* @param bool|float|int|string|null $value Config value.
*
* @return string
*/
protected function normalize( $type, $name, $value ) {
if ( 'constant' === $type ) {
$placeholder = "define( '%s', %s );";
} elseif ( 'variable' === $type ) {
$placeholder = '$%s = %s;';
} else {
throw new Exception( "Unable to normalize config type '{$type}'." );
}
return sprintf( $placeholder, $name, $value );
}
/**
* Parses the source of a wp-config.php file.
*
* @param string $src Config file source.
*
* @return array<string, array<string, array{src: string, value: string, parts: array<string>}>>
*/
protected function parse_wp_config( $src ) {
$configs = array();
$configs['constant'] = array();
$configs['variable'] = array();
// Strip comments.
foreach ( token_get_all( $src ) as $token ) {
if ( in_array( $token[0], array( T_COMMENT, T_DOC_COMMENT ), true ) ) {
if ( '//' === $token[1] ) {
// For empty line comments, actually remove empty line comments instead of all double-slashes.
// See: https://github.com/wp-cli/wp-config-transformer/issues/47
$src = (string) preg_replace( '/' . preg_quote( '//', '/' ) . '$/m', '', $src );
} else {
$src = str_replace( $token[1], '', $src );
}
}
}
preg_match_all( '/(?<=^|;|<\?php\s|<\?\s)(\h*define\s*\(\s*[\'"](\w*?)[\'"]\s*)(,\s*(\'\'|""|\'.*?[^\\\\]\'|".*?[^\\\\]"|.*?)\s*,?\s*)((?:,\s*(?:true|false)[,\s]*)?\)\s*;)/ims', $src, $constants );
preg_match_all( '/(?<=^|;|<\?php\s|<\?\s)(\h*\$(\w+)\s*=)(\s*(\'\'|""|\'.*?[^\\\\]\'|".*?[^\\\\]"|.*?)\s*;)/ims', $src, $variables );
if ( ! empty( $constants[0] ) && ! empty( $constants[1] ) && ! empty( $constants[2] ) && ! empty( $constants[3] ) && ! empty( $constants[4] ) && ! empty( $constants[5] ) ) {
foreach ( $constants[2] as $index => $name ) {
$configs['constant'][ $name ] = array(
'src' => $constants[0][ $index ],
'value' => $constants[4][ $index ],
'parts' => array(
$constants[1][ $index ],
$constants[3][ $index ],
$constants[5][ $index ],
),
);
}
}
if ( ! empty( $variables[0] ) && ! empty( $variables[1] ) && ! empty( $variables[2] ) && ! empty( $variables[3] ) && ! empty( $variables[4] ) ) {
// Remove duplicate(s), last definition wins.
$variables[2] = array_reverse( array_unique( array_reverse( $variables[2], true ) ), true );
foreach ( $variables[2] as $index => $name ) {
$configs['variable'][ $name ] = array(
'src' => $variables[0][ $index ],
'value' => $variables[4][ $index ],
'parts' => array(
$variables[1][ $index ],
$variables[3][ $index ],
),
);
}
}
return $configs;
}
/**
* Saves new contents to the wp-config.php file.
*
* @throws Exception If the config file content provided is empty.
* @throws Exception If there is a failure when saving the wp-config.php file.
*
* @param string $contents New config contents.
*
* @return bool
*/
protected function save( $contents ) {
if ( ! trim( $contents ) ) {
throw new Exception( 'Cannot save the config file with empty contents.' );
}
if ( $contents === $this->wp_config_src ) {
return false;
}
$result = file_put_contents( $this->wp_config_path, $contents, LOCK_EX );
if ( false === $result ) {
throw new Exception( 'Failed to update the config file.' );
}
return true;
}
}