Skip to content

Commit

Permalink
Refactor config_eval() to use PREG_SET_ORDER
Browse files Browse the repository at this point in the history
Call preg_match_all() with PREG_SET_ORDER flag instead of the default
PREG_PATTERN_ORDER allows simplification of the replacement loop using
a foreach.

Assign the resulting match array elements to named variables makes the
code self-documenting and easier to read.
  • Loading branch information
dregad committed Mar 28, 2020
1 parent 4800cfb commit f45ea66
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions core/config_api.php
Expand Up @@ -622,29 +622,35 @@ function env_obsolete( $p_env_variable, $p_new_env_variable ) {
function config_eval( $p_value, $p_global = false ) {
$t_value = $p_value;
if( !empty( $t_value ) && is_string( $t_value ) && !is_numeric( $t_value ) ) {
if( 0 < preg_match_all( '/(?:^|[^\\\\])(%([^%]+)%)/U', $t_value, $t_matches ) ) {
$t_count = count( $t_matches[0] );
for( $i = 0;$i < $t_count;$i++ ) {
$t_count = preg_match_all(
'/(?:^|[^\\\\])(%([^%]+)%)/U',
$t_value,
$t_matches,
PREG_SET_ORDER
);

if( $t_count > 0 ) {
foreach( $t_matches as $t_match ) {
list(, $t_match_with_delimiters, $t_config ) = $t_match;

# $t_matches[0][$i] is the matched string including the delimiters
# $t_matches[1][$i] is the target parameter string
if( $p_global ) {
$t_repl = config_get_global( $t_matches[2][$i] );
$t_repl = config_get_global( $t_config );
} else {
$t_repl = config_get( $t_matches[2][$i] );
$t_repl = config_get( $t_config );
}

# Handle the simple case where there is no need to do string replace.
# This will resolve the case where the $t_repl value is of non-string
# type, e.g. array of access levels.
if( $t_count == 1 && $p_value == '%' . $t_matches[2][$i] . '%' ) {
if( $t_count == 1 && $p_value == $t_match_with_delimiters ) {
$t_value = $t_repl;
break;
}

$t_value = str_replace( $t_matches[1][$i], $t_repl, $t_value );
$t_value = str_replace( $t_match_with_delimiters, $t_repl, $t_value );
}
}

# Remove escaped '%'
$t_value = str_replace( '\\%', '%', $t_value );
}
Expand Down

0 comments on commit f45ea66

Please sign in to comment.