Skip to content

More precise hrtime() return type#4353

Open
takaram wants to merge 1 commit intophpstan:2.1.xfrom
takaram:improve-hrtime
Open

More precise hrtime() return type#4353
takaram wants to merge 1 commit intophpstan:2.1.xfrom
takaram:improve-hrtime

Conversation

@takaram
Copy link
Contributor

@takaram takaram commented Sep 20, 2025

hrtime(true) always returns positive-int.
hrtime(false) returns an array of [second, nanosecond], where second is positive-int and nanosecond is between 0 and 10⁹-1 (because 10⁹ nanosecond = 1 second)

Another solution

I tried to remove the return type extension and add a stub like this:

/**
 * @template T of bool
 * @param T $as_number
 * @return (T is true ? __benevolent<float|positive-int> : array{positive-int, int<0, 999999999>})
 */
function hrtime(bool $as_number = false): array|int|float {}

but this doesn't work:

dumpType(hrtime()); // array{int<1, max>, int<0, 999999999>}|false
dumpType(hrtime(true)); // float|int<1, max>|false

false seems to come from phpstan/php-8-stubs.
https://github.com/phpstan/php-8-stubs/blob/0.4.30/stubs/ext/standard/hrtime.php


I also tried this stub:

/**
 * @template T of bool
 * @param T $as_number
 * @return (T is true ? __benevolent<float|positive-int> : (T is false ? array{positive-int, int<0, 999999999>} : false))
 */
function hrtime(bool $as_number = false): array|int|float|false {}

This works in most cases, but we see false when argument is not bool:

// before: array{int, int}|float|int
// after:  array{int<1, max>, int<0, 999999999>}|float|int<1, max>|false
dumpType(hrtime(1));

@ondrejmirtes
Copy link
Member

I'm sorry for not looking at this sooner, please rebase and fix the conflict.

@takaram
Copy link
Contributor Author

takaram commented Feb 5, 2026

@ondrejmirtes
I rebased the branch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants