Skip to content

Commit bed0a3a

Browse files
westonruterclaude
andcommitted
Date/Time: Return false from wp_date() when the timestamp cannot be parsed.
`wp_date()` only checked the timestamp with `is_numeric()`, which accepts values that `date_create( '@' . $timestamp )` rejects, such as `'1e3'`, `1e20`, `' 5'`, and `'.5'`. For those, `date_create()` returned false and the following `setTimezone()` call caused a fatal error. Now false is returned, as documented for invalid timestamp input and as already done for non-numeric input. This also resolves the PHPStan `method.nonObject` errors on every use of `$datetime` in the function. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent fbd1a8e commit bed0a3a

2 files changed

Lines changed: 31 additions & 0 deletions

File tree

‎src/wp-includes/functions.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,11 @@ function wp_date( $format, $timestamp = null, $timezone = null ) {
258258
}
259259

260260
$datetime = date_create( '@' . $timestamp );
261+
262+
if ( false === $datetime ) {
263+
return false;
264+
}
265+
261266
$datetime->setTimezone( $timezone );
262267

263268
if ( empty( $wp_locale->month ) || empty( $wp_locale->weekday ) ) {

‎tests/phpunit/tests/date/wpDate.php‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,32 @@ public function test_should_return_false_on_invalid_timestamp() {
3434
$this->assertFalse( wp_date( DATE_RFC3339, 'invalid' ) );
3535
}
3636

37+
/**
38+
* Tests that a numeric timestamp which {@see date_create()} cannot parse returns false.
39+
*
40+
* @dataProvider data_should_return_false_on_unparsable_numeric_timestamp
41+
*
42+
* @param int|float|string $timestamp Numeric timestamp.
43+
*/
44+
public function test_should_return_false_on_unparsable_numeric_timestamp( $timestamp ): void {
45+
$this->assertTrue( is_numeric( $timestamp ), 'Expected the timestamp to pass the is_numeric() check.' );
46+
$this->assertFalse( wp_date( DATE_RFC3339, $timestamp ) ); // @phpstan-ignore argument.type (Intentionally invalid input.)
47+
}
48+
49+
/**
50+
* Data provider for {@see self::test_should_return_false_on_unparsable_numeric_timestamp()}.
51+
*
52+
* @return array<non-falsy-string, array{ 0: int|float|string }>
53+
*/
54+
public static function data_should_return_false_on_unparsable_numeric_timestamp(): array {
55+
return array(
56+
'exponent notation' => array( '1e3' ),
57+
'out-of-range float' => array( 1e20 ),
58+
'leading whitespace' => array( ' 5' ),
59+
'leading decimal' => array( '.5' ),
60+
);
61+
}
62+
3763
/**
3864
* @ticket 48319
3965
*/

0 commit comments

Comments
 (0)