Automattic\WooCommerce\Blueprint
ClassExtractor::apply_variable_replacement
Applies a replacement to a variable in a specific method.
Method of the class: ClassExtractor{}
No Hooks.
Returns
String
. The updated file content.
Usage
// private - for code of main (parent) class only $result = $this->apply_variable_replacement( $file_content, $method_name, $variable_name, $new_value );
- $file_content(string) (required)
- The content of the PHP file.
- $method_name(string) (required)
- The name of the method containing the variable.
- $variable_name(string) (required)
- The name of the variable to replace.
- $new_value(mixed) (required)
- The new value for the variable.
ClassExtractor::apply_variable_replacement() ClassExtractor::apply variable replacement code WC 9.9.5
private function apply_variable_replacement( $file_content, $method_name, $variable_name, $new_value ) { $pattern = '/function\s+' . preg_quote( $method_name, '/' ) . '\s*\([^)]*\)\s*\{\s*(.*?)\s*\}/s'; if ( preg_match( $pattern, $file_content, $matches ) ) { $method_body = $matches[1]; // Security check: Check if it's necessary to use var_export. $new_value_exported = var_export( $new_value, true ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export $variable_pattern = '/\$' . preg_quote( $variable_name, '/' ) . '\s*=\s*[^;]+;/'; $replacement = '$' . $variable_name . ' = ' . $new_value_exported . ';'; $updated_method_body = preg_replace( $variable_pattern, $replacement, $method_body, 1 ); if ( null !== $updated_method_body ) { $file_content = str_replace( $method_body, $updated_method_body, $file_content ); } } return $file_content; }