[wp-trac] [WordPress Trac] #55962: Upgrade `sanitize_hex_color()` to CSS Color Level 4

WordPress Trac noreply at wordpress.org
Sun Jun 12 04:17:17 UTC 2022


#55962: Upgrade `sanitize_hex_color()` to CSS Color Level 4
-------------------------------------------------+-------------------------
 Reporter:  anrghg                               |       Owner:  (none)
     Type:  enhancement                          |      Status:  new
 Priority:  normal                               |   Milestone:  Future
                                                 |  Release
Component:  Formatting                           |     Version:
 Severity:  normal                               |  Resolution:
 Keywords:  needs-patch needs-unit-tests dev-    |     Focuses:  css
  feedback                                       |
-------------------------------------------------+-------------------------
Changes (by costdev):

 * keywords:  needs-patch needs-unit-tests => needs-patch needs-unit-tests
     dev-feedback


Comment:

 @ocean90 What if we changed the signature of `sanitize_hex_color()` to
 include an optional `$maybe_alpha` argument that defaults to `false`? That
 way, `$maybe_alpha` is only enabled by intent, and this should protect BC.

 Instead of working with complicated regex patterns, we could also simplify
 the function by:
 1. Performing a length check, dependent on the value of `$maybe_alpha`.
 2. Strip invalid characters and compare the result to the original value.

 For example:

 {{{#!php
 function sanitize_hex_color( $color, $maybe_alpha = false ) {
     if ( '' === $color ) {
         return '';
     }

     $allowed_lengths = $maybe_alpha ? array( 4, 5, 7, 9 ) : array( 4, 7 );
     $correct_length  = in_array( strlen( $color ), $allowed_lengths, true
 );

     if ( $correct_length && preg_replace( '|^#([^A-Fa-f0-9]+)$|', '',
 $color ) === $color ) {
         return $color;
     }
 }
 }}}

 [https://3v4l.org/4s5Q6 Tests in 3val]

 This would also mean that we don't have to struggle against "naming is
 hard", because `sanitize_hex_with_alpha_color()` suggests it must have
 alpha, which means checking a valid hex colour code would require a call
 to both functions instead of just calling the revised
 `sanitize_hex_color()` above.

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


More information about the wp-trac mailing list