What does TREAT_AS_NON_EMPTY do?

92 views Asked by At

The tool rector has a configuration option for certain rules called TREAT_AS_NON_EMPTY. For example, https://github.com/rectorphp/rector/blob/main/docs/rector_rules_overview.md#disallowedemptyrulefixerrector

What does this configuration actually do?

1

There are 1 answers

5
Barmar On

Depending on which rules you use this setting for, it performs any of the following refactors:

BooleanInBooleanNotRuleFixerRector: !$string_or_null => $string === null
BooleanInIfConditionRuleFixerRector: if ($string) => if ($string !== '')
BooleanInTernaryOperatorRuleFixerRector: $array ? 1 : 2 => $array !== [] ? 1 : 2
DisallowedEmptyRuleFixerRector: empty($array) => $array === []
DisallowedShortTernaryRuleFixerRector: $array ?: 2 => $array !== [] ? $array : 2

The general idea is that it replaces implicit conversions of types to booleans with explicit comparisons with the empty value.

The first transformation also avoids treating an empty string as falsey. The assumption being that when you declare the variable's type as string|null, you didn't intend for an empty string to be treated equivalent to null.