Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 32 additions & 8 deletions src/EvalFile_Command.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,28 @@
<?php

use WP_CLI\Utils;

class EvalFile_Command extends WP_CLI_Command {

/**
* Regular expression pattern to match the shell shebang.
*
* @var string
*/
const SHEBANG_PATTERN = '/^(#!.*)$/m';

/**
* Regular expression pattern to match __FILE__ and __DIR__ constants.
*
* We try to be smart and only replace the constants when they are not within quotes.
* Regular expressions being stateless, this is probably not 100% correct for edge cases.
*
* @see https://regex101.com/r/9hXp5d/4/
*
* @var string
*/
const FILE_DIR_PATTERN = '/(?>\'[^\']*?\')|(?>"[^"]*?")|(?<file>\b__FILE__\b)|(?<dir>\b__DIR__\b)/m';

/**
* Loads and executes a PHP file.
*
Expand Down Expand Up @@ -32,34 +53,37 @@ public function __invoke( $args, $assoc_args ) {
WP_CLI::error( "'$file' does not exist." );
}

if ( null === \WP_CLI\Utils\get_flag_value( $assoc_args, 'skip-wordpress' ) ) {
if ( null === Utils\get_flag_value( $assoc_args, 'skip-wordpress' ) ) {
WP_CLI::get_runner()->load_wordpress();
}

self::execute_eval( $file, $args );
}

/**
* Evaluate a provided file.
*
* @param string $file Filepath to execute, or - for STDIN.
* @param mixed $args Array of positional arguments to pass to the file.
*/
private static function execute_eval( $file, $args ) {
if ( '-' === $file ) {
eval( '?>' . file_get_contents( 'php://stdin' ) );
} else {
$file_contents = file_get_contents( $file );

// Check for and remove she-bang.
if ( 0 === strpos( $file_contents, '#!' ) ) {
$file_contents = preg_replace( '/^(#!.*)$/im', '', $file_contents );
if ( 0 === strncmp( $file_contents, '#!', 2 ) ) {
$file_contents = preg_replace( static::SHEBANG_PATTERN, '', $file_contents );
}

$file = realpath( $file );
$dir = dirname( $file );

// Replace __FILE__ and __DIR__ constants with value of $file or $dir.
// We try to be smart and only replace the constants when they are not within quotes.
// Regular expressions being stateless, this is probably not 100% correct for edge cases.
// See https://regex101.com/r/9hXp5d/2/
$file_contents = preg_replace_callback(
'/(?>\'[^\']*?\')|(?>"[^"]*?")|(?<file>__FILE__)|(?<dir>__DIR__)/m',
function ( $matches ) use ( $file, $dir ) {
static::FILE_DIR_PATTERN,
static function ( $matches ) use ( $file, $dir ) {
if ( ! empty( $matches['file'] ) ) {
return "'{$file}'";
}
Expand Down