Skip to content

Commit dcda021

Browse files
authored
Merge pull request #59 from wp-cli/fix/reuse-framework-replacement
Reuse `Utils\replace_path_consts()` for magic constants
2 parents be15c7d + d681c9c commit dcda021

2 files changed

Lines changed: 6 additions & 33 deletions

File tree

src/EvalFile_Command.php

Lines changed: 3 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,6 @@ class EvalFile_Command extends WP_CLI_Command {
1111
*/
1212
const SHEBANG_PATTERN = '/^(#!.*)$/m';
1313

14-
/**
15-
* Regular expression pattern to match __FILE__ and __DIR__ constants.
16-
*
17-
* We try to be smart and only replace the constants when they are not within quotes.
18-
* Regular expressions being stateless, this is probably not 100% correct for edge cases.
19-
*
20-
* @see https://regex101.com/r/9hXp5d/4/
21-
*
22-
* @var string
23-
*/
24-
const FILE_DIR_PATTERN = '/(?>\'[^\']*?\')|(?>"[^"]*?")|(?<file>\b__FILE__\b)|(?<dir>\b__DIR__\b)/m';
25-
2614
/**
2715
* Loads and executes a PHP file.
2816
*
@@ -72,31 +60,14 @@ private static function execute_eval( $file, $args ) {
7260
} else {
7361
$file_contents = file_get_contents( $file );
7462

63+
// Adjust for __FILE__ and __DIR__ magic constants.
64+
$file_contents = Utils\replace_path_consts( $file_contents, $file );
65+
7566
// Check for and remove she-bang.
7667
if ( 0 === strncmp( $file_contents, '#!', 2 ) ) {
7768
$file_contents = preg_replace( static::SHEBANG_PATTERN, '', $file_contents );
7869
}
7970

80-
$file = realpath( $file );
81-
$dir = dirname( $file );
82-
83-
// Replace __FILE__ and __DIR__ constants with value of $file or $dir.
84-
$file_contents = preg_replace_callback(
85-
static::FILE_DIR_PATTERN,
86-
static function ( $matches ) use ( $file, $dir ) {
87-
if ( ! empty( $matches['file'] ) ) {
88-
return "'{$file}'";
89-
}
90-
91-
if ( ! empty( $matches['dir'] ) ) {
92-
return "'{$dir}'";
93-
}
94-
95-
return $matches[0];
96-
},
97-
$file_contents
98-
);
99-
10071
eval( '?>' . $file_contents );
10172
}
10273
}

src/Eval_Command.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
<?php
22

3+
use WP_CLI\Utils;
4+
35
class Eval_Command extends WP_CLI_Command {
46

57
/**
@@ -30,7 +32,7 @@ class Eval_Command extends WP_CLI_Command {
3032
*/
3133
public function __invoke( $args, $assoc_args ) {
3234

33-
if ( null === \WP_CLI\Utils\get_flag_value( $assoc_args, 'skip-wordpress' ) ) {
35+
if ( null === Utils\get_flag_value( $assoc_args, 'skip-wordpress' ) ) {
3436
WP_CLI::get_runner()->load_wordpress();
3537
}
3638

0 commit comments

Comments
 (0)