-1

Would anyone know how we can rewrite the following function to be compatible and work with PHP 8?

function wpsc_have_shipping_quote() {

    $has_quote = false;

    global $wpsc_cart;

    if ( $wpsc_cart->shipping_quote_count > 0 || count( $wpsc_cart->shipping_quotes ) > 0 ) {
        $has_quote = true;
    }

    return $has_quote;
}
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
Andy
  • 23
  • 2
  • 7
  • 2
    What's wrong with that function as it stands? I'm not seeing anything jumping out at me. Are you getting an error when you use it? – Chris Haas Jan 28 '22 at 18:01
  • 1
    What does not work with this? – esQmo_ Jan 28 '22 at 18:01
  • Hi there, sorry forgot to post the error message, which is:Fatal error: Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, null given – Andy Jan 28 '22 at 18:22
  • Before upgrading the PHP version of a site, always turn PHP errors completely on. This has been a warning since 7.2 with a plan to turn it into a full error in 8.0. – Chris Haas Jan 28 '22 at 18:31
  • Thanks Chris, Luckily we're doing this in a test environment at the moment. Currently trying to upgrade from PHP7.4 to PHP8.0. The other section of code with the $value mentioned is: function wpsc_shipping_quote_value( $numeric = false ) { global $wpsc_cart; $value = apply_filters( 'wpsc_shipping_quote_value', $wpsc_cart->shipping_quote['value'] ); return ( $numeric ) ? $value : wpsc_currency_display( $value ); } – Andy Jan 28 '22 at 18:34
  • 2
    Assuming `$wpsc_cart->shipping_quotes` is an array and not an exotic object, you can simply check for `!empty($wpsc_cart->shipping_quotes)` which will return true if 1 or more, and false on 0 or null. – Markus AO Jan 28 '22 at 18:56

2 Answers2

2

You don't have to count the array just to see if it has anything in it. When you use ||, the values being compared will be converted to booleans, and shipping_quotes will evaluate to false whether it is an empty array or a null.

function wpsc_have_shipping_quote() {    

    global $wpsc_cart;

    return $wpsc_cart->shipping_quote_count || $wpsc_cart->shipping_quotes;
}

This should work in any PHP version.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
1

Andy. Kind regards.

In PHP 8.+, count() does not accept null values anymore, it was already throwing warnings since PHP 7.2 if I recall correctly. Therefore the code is failing exactly here:

count( $wpsc_cart->shipping_quotes ) > 0

because in some situations $wpsc_cart->shipping_quotes may be null (it was not set).

You can use the new PHP 8 null coalescing to check if the value is null, and if it is null, you can provide an empty array []. So change the line:

if ( $wpsc_cart->shipping_quote_count > 0 || count( $wpsc_cart->shipping_quotes ) > 0 ) {

To:

if ( $wpsc_cart->shipping_quote_count > 0 || count( $wpsc_cart->shipping_quotes ?? [] ) > 0 ) {
Rodrigo Kravetz
  • 382
  • 1
  • 11