Make WordPress Core

Changeset 62719


Ignore:
Timestamp:
07/14/2026 04:35:26 AM (4 months ago)
Author:
westonruter
Message:

Code Modernization: Add a polyfill for PHP 8.6's clamp().

Introduce a clamp() polyfill in compat.php so that core, plugins, and themes can call the function on every supported PHP version without a version check. It returns the value when it lies within the bounds and the nearest bound otherwise, and throws a ValueError when $min is greater than $max or when either bound is NAN. On PHP 7.x, an InvalidArgumentException is thrown instead, since the ValueError class does not yet exist.

Adopt the function at the two places in core that were clamping via a nested min( max( … ) ): the oEmbed response width in get_oembed_response_data(), and the minimum font size factor in wp_get_typography_font_size_value().

Additionally, fix PHPStan errors in code that touches the newly-introduced clamp() usage. Add types to wp_get_typography_value_and_unit() and refactor the parsing to allow static analysis to identify the shape of $matches and avoid issues with passing special regex characters in units.

Developed in ​https://github.com/WordPress/wordpress-develop/pull/11669.
Follow-up to r35436, r54260, r55947.

Props soean, mukesh27, westonruter.
See #64898.
Fixes #65143.

Location:
trunk
Files:
1 added
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/phpstan.neon.dist

    r62618 r62719  
    4141                        path: src/wp-includes/canonical.php
    4242                        count: 1
     43                # Level 2:
     44                # ValueError is PHP 8.0+; core throws it conditionally so the docblocks are correct for WP's 7.4+ range,
     45                # but bleedingEdge's version-aware check treats the class as non-existent against the PHP 7.4 floor.
     46                -
     47                        message: '#^PHPDoc tag @throws with type InvalidArgumentException\|ValueError is not subtype of Throwable$#'
     48                        path: src/wp-includes/compat.php
     49                        reportUnmatched: false
  • trunk/src/wp-includes/block-supports/typography.php

    r61632 r62719  
    359359 * @return array|null An array consisting of `'value'` and `'unit'` properties on success.
    360360 *                    `null` on failure.
     361 * @phpstan-param array{
     362 *     coerce_to?: string,
     363 *     root_size_value?: positive-int,
     364 *     acceptable_units?: non-empty-array<non-empty-string>,
     365 * } $options
     366 * @phpstan-return array{ value: float, unit: non-empty-string }|null
    361367 */
    362 function wp_get_typography_value_and_unit( $raw_value, $options = array() ) {
     368function wp_get_typography_value_and_unit( $raw_value, $options = array() ): ?array {
    363369        if ( ! is_string( $raw_value ) && ! is_int( $raw_value ) && ! is_float( $raw_value ) ) {
    364370                _doing_it_wrong(
    … …  
    385391        );
    386392
     393        /**
     394         * @var array{
     395         *     coerce_to: string,
     396         *     root_size_value: positive-int,
     397         *     acceptable_units: non-empty-array<non-empty-string>,
     398         * } $options
     399         */
    387400        $options = wp_parse_args( $options, $defaults );
    388401
    389         $acceptable_units_group = implode( '|', $options['acceptable_units'] );
    390         $pattern                = '/^(\d*\.?\d+)(' . $acceptable_units_group . '){1,1}$/';
    391 
    392         preg_match( $pattern, $raw_value, $matches );
    393 
    394         // Bails out if not a number value and a px or rem unit.
    395         if ( ! isset( $matches[1] ) || ! isset( $matches[2] ) ) {
     402        // Bails out if the raw value can't be parsed.
     403        if ( ! preg_match( '/^(\d*\.?\d+)([a-zA-Z]+|%)$/', $raw_value, $matches ) ) {
    396404                return null;
    397405        }
    398406
    399         $value = $matches[1];
     407        $value = (float) $matches[1];
    400408        $unit  = $matches[2];
     409
     410        if ( ! in_array( $unit, $options['acceptable_units'], true ) ) {
     411                return null;
     412        }
    401413
    402414        /*
    … …  
    670682                 * The scale factor is constrained between min and max values.
    671683                 */
    672                 $minimum_font_size_factor     = min( max( 1 - 0.075 * log( $preferred_font_size_in_px, 2 ), $default_minimum_font_size_factor_min ), $default_minimum_font_size_factor_max );
     684                $minimum_font_size_factor     = clamp( 1 - 0.075 * log( $preferred_font_size_in_px, 2 ), $default_minimum_font_size_factor_min, $default_minimum_font_size_factor_max );
    673685                $calculated_minimum_font_size = round( $preferred_size['value'] * $minimum_font_size_factor, 3 );
    674686
  • trunk/src/wp-includes/compat.php

    r62576 r62719  
    686686}
    687687
     688if ( ! function_exists( 'clamp' ) ) {
     689        /**
     690         * Polyfill for `clamp()` function added in PHP 8.6.
     691         *
     692         * Clamps a value to be within the range of a given minimum and maximum.
     693         *
     694         * If the value is within the bounds, the original value is returned.
     695         * If it is not within the bounds, the closest bound is returned.
     696         *
     697         * @since 7.1.0
     698         *
     699         * @param mixed $value The value to clamp.
     700         * @param mixed $min   The minimum bound. Must be less than or equal to `$max`.
     701         * @param mixed $max   The maximum bound. Must be greater than or equal to `$min`.
     702         * @return mixed The clamped value. Either `$value`, `$min`, or `$max`.
     703         *
     704         * @throws ValueError               If `$min` is greater than `$max`, or if `$min` or `$max` is NAN, and the ValueError class exists (PHP 8.0+ or polyfilled).
     705         * @throws InvalidArgumentException If `$min` is greater than `$max`, or if `$min` or `$max` is NAN, and the ValueError class does not exist (PHP 7.x).
     706         *
     707         * @phpstan-template TValue
     708         * @phpstan-template TMin
     709         * @phpstan-template TMax
     710         * @phpstan-param TValue $value
     711         * @phpstan-param TMin   $min
     712         * @phpstan-param TMax   $max
     713         * @phpstan-return TValue|TMin|TMax
     714         */
     715        function clamp( $value, $min, $max ) {
     716                $throw_value_error = static function ( string $message ) {
     717                        // The ValueError class was introduced in PHP 8, so in 7.4 throw InvalidArgumentException instead.
     718                        if ( ! class_exists( 'ValueError', false ) ) {
     719                                throw new InvalidArgumentException( $message );
     720                        }
     721                        throw new ValueError( $message );
     722                };
     723
     724                if ( is_float( $min ) && is_nan( $min ) ) {
     725                        $throw_value_error( 'clamp(): Argument #2 ($min) must not be NAN' );
     726                }
     727
     728                if ( is_float( $max ) && is_nan( $max ) ) {
     729                        $throw_value_error( 'clamp(): Argument #3 ($max) must not be NAN' );
     730                }
     731
     732                if ( $max < $min ) {
     733                        $throw_value_error( 'clamp(): Argument #2 ($min) must be smaller than or equal to argument #3 ($max)' );
     734                }
     735
     736                /*
     737                 * The upper bound is checked before the lower bound to match the order in PHP's
     738                 * implementation. Comparison in PHP is not transitive when operands of different
     739                 * types are mixed (for example, comparing against a bool coerces both operands to
     740                 * bool), so both bounds can compare as exceeded at once, and the first check wins.
     741                 */
     742                if ( $value > $max ) {
     743                        return $max;
     744                }
     745
     746                if ( $value < $min ) {
     747                        return $min;
     748                }
     749
     750                return $value;
     751        }
     752}
     753
    688754// IMAGETYPE_AVIF constant is only defined in PHP 8.x or later.
    689755if ( ! defined( 'IMAGETYPE_AVIF' ) ) {
  • trunk/src/wp-includes/embed.php

    r62521 r62719  
    595595        );
    596596
    597         $width  = min( max( $min_max_width['min'], $width ), $min_max_width['max'] );
     597        /** @var array{ min: positive-int, max: positive-int } $min_max_width */
     598        $width  = clamp( $width, $min_max_width['min'], $min_max_width['max'] );
    598599        $height = max( (int) ceil( $width / 16 * 9 ), 200 );
    599600
Note: See TracChangeset for help on using the changeset viewer.