[wp-trac] [WordPress Trac] #54149: Audit `get_comment()` response checks.

WordPress Trac noreply at wordpress.org
Fri Nov 5 01:38:41 UTC 2021


#54149: Audit `get_comment()` response checks.
----------------------------+-------------------------------
 Reporter:  costdev         |       Owner:  (none)
     Type:  task (blessed)  |      Status:  new
 Priority:  normal          |   Milestone:  5.9
Component:  Comments        |     Version:  trunk
 Severity:  normal          |  Resolution:
 Keywords:  has-patch       |     Focuses:  coding-standards
----------------------------+-------------------------------

Comment (by dd32):

 Replying to [comment:4 jrf]:
 > When validating data and given the choice between checking ''what you
 want'' and checking ''what you don't want'', it's best practice to always
 use the most specific check (which still doesn't break BC), which in this
 case means that (variations of) `if ( $comment instanceof WP_Comment ) {}`
 should be the preferred check.

 Respectfully, I disagree that `$comment instanceof WP_Comment` should be
 the preferred check - especially in older code or anything that isn't
 using it in any overly strict manner.
 When you're dealing with the response of `get_comment()` you're going to
 end up with several variations:
  - false/null - falsy values
  - WP_Comment - the usual expected value, truthy.
  - Something else from a function filtering it. These break down to:
    - Code errors returning true, arrays, or objects that are not at all
 like WP_Comments, these are code errors on the developers that shouldn't
 need to be cared about
    - Something Comment-like, I've seen plugins return "fake" comments that
 are just `stdClass` (from before WP_Comment existed) that for all intents
 and purposes are comment-like enough.

 Based on a truth-table of that, you effectively are dealing with three
 variations:
  - Truthy valid values = stdClass / WP_Comment
  - Falsy values = null/false
  - Invalid junk that a plugin has returned, that we shouldn't need care
 about, let it throw whatever PHP Notice/Warning/Error here and the
 developer of the plugin or code can fix it.

 While I get it, that `$comment instanceOf WP_Comment` or `is_object(
 $comment )` are the most "correct and strict" checks, `if ( $comment )` is
 for all intents and purposes "enough" for checking if the comment is valid
 within WordPress code IMHO.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/54149#comment:9>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list