[wp-trac] [WordPress Trac] #40280: Short-circuit filters can't return common values

WordPress Trac noreply at wordpress.org
Mon Mar 27 19:09:12 UTC 2017


#40280: Short-circuit filters can't return common values
-------------------------+-----------------------------
 Reporter:  andy         |      Owner:
     Type:  enhancement  |     Status:  new
 Priority:  normal       |  Milestone:  Awaiting Review
Component:  General      |    Version:  trunk
 Severity:  normal       |   Keywords:
  Focuses:               |
-------------------------+-----------------------------
 #37930 contemplates adding another short-circuit filter, `pre_option`.
 This follows a pattern that is already duplicated several times and even
 somewhat fragmented in its implementations.

 The short-circuit filter pattern has this problem: the return value is
 overloaded. Its meaning is either "nothing changed" or "this is the new
 value" and there are collisions between these meanings in cases where you
 might want to short-circuit-return `false` or `null`, depending on which
 short-circuit filter is being used. One proposed improvement is to use
 only `null` as the value meaning "nothing changed", as this is less likely
 than `false` is to be a value in any short-circuit situation.

 The pattern using `null` can be formalized in a new function that does not
 overload the return value. This is accomplished by returning multiple
 values, which we can do in PHP by reference passing. A simple
 implementation using `null` and a usage example:

 {{{
 function apply_filters_pre( $filter, &$value ) {
         $value = apply_filters( $filter, null );
         return !is_null( $value );
 }

 if ( apply_filters_pre( 'get_option_pre', $value ) ) {
         return $value;
 }
 }}}

 (Other proposed function names include `if_apply_filters` and
 `apply_filters_short_circuit`.)

 This centralizes the pattern and its documentation to a single core
 function, encapsulates the overloaded parameter as an implementation
 detail, and simplifies every existing and future call site. The diff would
 be net red. However, we are still unable to return `null` from a short-
 circuit position, which becomes a plausible use case if we enshrine this
 pattern in a core function. The collision space can be minimized by using
 a special type used nowhere else:

 {{{
 class WP_Unfiltered_Value {}

 function apply_filters_pre( $filter, &$value ) {
         $value = apply_filters( $filter, new WP_Unfiltered_Value );
         return !is_object( $value ) || !is_a( $value,
 'WP_Unfiltered_Value' );
 }
 }}}

--
Ticket URL: <https://core.trac.wordpress.org/ticket/40280>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list