smarty icon indicating copy to clipboard operation
smarty copied to clipboard

modifier default not working with @ suppression

Open alabama opened this issue 9 years ago • 6 comments

The default modifier just access the tpl_vars array with the non existing key and tries to suppress the error outcome with '@' like: $tmp = @$_smarty_tpl->tpl_vars['bShowInfo']->value

This won't work in PHP >= 5.4 (5.3 as well?) There should be at least an "array_key_exist | isset" check to get the functionality right

alabama avatar Feb 22 '17 08:02 alabama

Is it possible to get rid of suppression in 'default'? This behavior is very disturbing during debugging through xDebug =(

Miksser avatar Oct 17 '18 13:10 Miksser

Is it possible to get rid of suppression in 'default'? This behavior is very disturbing during debugging through xDebug =(

Miksser avatar Oct 17 '18 13:10 Miksser

Had the same issue when debuging, I had a lots of notices in the console. Plus a possible performance loss from the notice being issued ( https://stackoverflow.com/questions/1868874/does-php-run-faster-without-warnings )

Maybe it's worth changing the original function? Until then here's my workaround

/**
 * Overwrites smarty's default modifier
 * Original function used $tmp = @$_smarty_tpl->tpl_vars['param0']->value)===null||$tmp==='' ? $_smarty_tpl->tpl_vars[param1'']->value : $tmp)
 * Witch throws a notice that is silenced
 * @param array $params
 * @return mixed|string
 */
function smartyDefault( $params )
{
    $default = $params[1] ?? '';
    return "( isset({$params[0]}) && {$params[0]} !== '' ) ? {$params[0]} : {$default}";
}

 $smarty->registerPlugin('modifiercompiler', 'default', 'smartyDefault' );

antman3351 avatar May 20 '19 14:05 antman3351

@Miksser @antman3351 I've added an empty check for variables for |default modifier in #650 . It does not appear to break anything. Can you confirm this fixes your problem?

wisskid avatar Mar 22 '21 11:03 wisskid

I just had a quick look at the change, so I might have missed something, but doesn't this change the behaviour of the default modifier? before default was used for unset variable, null or an empty string. Using empty() default would also be applied to false, 0 , '0' and [ ].

antman3351 avatar Mar 22 '21 12:03 antman3351

Well spotted, @antman3351 ! Not sure how that got past me. I thought I ran the new unit tests against the old code (seeing no change in behavior) but I must have somehow messed that up. Added the 0, '0' and [] cases to the unit tests and fixed the implementation. Is this better?

wisskid avatar Mar 22 '21 23:03 wisskid

The default modifier has already been changed to longer use the @ modifier in https://github.com/smarty-php/smarty/pull/629

wisskid avatar Sep 22 '22 22:09 wisskid