WordPress.org

Make WordPress Core

Changeset 51619


Ignore:
Timestamp:
08/16/2021 03:22:38 PM (5 weeks ago)
Author:
SergeyBiryukov
Message:

Code Modernization: Check the return type of _get_cron_array() in wp_schedule_event().

This fixes a "Deprecated: Automatic conversion of false to array is deprecated" warning on PHP 8.1.

In wp_schedule_event(), the cron info array is retrieved via a call to _get_cron_array(), but as the documentation (correctly) states, the return type of that function is array|false, where false is returned for a virgin site, with no cron jobs scheduled yet.

However, no type check is done on the return value, and the wp_schedule_event() function just blindly continues by assigning a value to a subkey of the $crons "array".

Fixed by adding validation for the returned value from _get_cron_array() and initializing an empty array if false was returned.

Reference: WordPress Developer Resources: _get_cron_array()

Props jrf, hellofromTonya, lucatume, pbearne, iluy, pedromendonca, SergeyBiryukov.
See #53635.

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/cron.php

    r50394 r51619  
    303303
    304304    $crons = _get_cron_array();
     305    if ( ! is_array( $crons ) ) {
     306        $crons = array();
     307    }
     308
    305309    $crons[ $event->timestamp ][ $event->hook ][ $key ] = array(
    306310        'schedule' => $event->schedule,
     
    11261130
    11271131    $crons = _get_cron_array();
    1128 
    1129     if ( false === $crons ) {
     1132    if ( ! is_array( $crons ) ) {
    11301133        return array();
    11311134    }
  • trunk/tests/phpunit/tests/cron.php

    r51568 r51619  
    9999
    100100        $this->assertSame( $recur, wp_get_schedule( $hook, $args ) );
    101 
     101    }
     102
     103
     104    /**
     105     * Tests that a call to wp_schedule_event() on a site without any scheduled events
     106     * does not result in a PHP deprecation warning on PHP 8.1 or higher.
     107     *
     108     * The warning that we should not see:
     109     * `Deprecated: Automatic conversion of false to array is deprecated`.
     110     *
     111     * @ticket 53635
     112     *
     113     * @covers ::wp_schedule_event
     114     */
     115    function test_wp_schedule_event_without_cron_option_does_not_throw_warning() {
     116        delete_option( 'cron' );
     117
     118        // Verify that the cause of the error is in place.
     119        $this->assertFalse( _get_cron_array(), '_get_cron_array() does not return false' );
     120
     121        $hook      = __FUNCTION__;
     122        $timestamp = strtotime( '+10 minutes' );
     123
     124        // Add an event.
     125        $this->assertTrue( wp_schedule_event( $timestamp, 'daily', $hook ) );
    102126    }
    103127
Note: See TracChangeset for help on using the changeset viewer.