WP_CLI\Utils

replace_path_consts()WP-CLI 1.0

Replace magic constants in some PHP source code.

Replaces the __FILE__ and __DIR__ magic constants with the values they are supposed to represent at runtime.

No Hooks.

Return

String. Adapted PHP code.

Usage

replace_path_consts( $source, $path );
$source(string) (required)
The PHP code to manipulate.
$path(string) (required)
The path to use instead of the magic constants.

replace_path_consts() code WP-CLI 2.8.0-alpha

function replace_path_consts( $source, $path ) {
	// Solve issue with Windows allowing single quotes in account names.
	$file = addslashes( $path );

	if ( file_exists( $file ) ) {
		$file = realpath( $file );
	}

	$dir = dirname( $file );

	// Replace __FILE__ and __DIR__ constants with value of $file or $dir.
	return preg_replace_callback(
		FILE_DIR_PATTERN,
		static function ( $matches ) use ( $file, $dir ) {
			if ( ! empty( $matches['file'] ) ) {
				return "'{$file}'";
			}

			if ( ! empty( $matches['dir'] ) ) {
				return "'{$dir}'";
			}

			return $matches[0];
		},
		$source
	);
}