callable parameter with any number of arguments #6813
-
Hi, Is there a way to tell PHPStan that a I'm trying to document a function that wrap a https://phpstan.org/r/35ebc5d4-35cf-4460-9809-ce7000f17621 I tried with variadics, but the meaning is not the same, so this also cause errors: https://phpstan.org/r/6bed2532-2446-4369-becd-57ae77113757 The next step would be to tell PHPStan that the returned callable have the same arguments as the one in parameter, but I don't think it's possible with template presently, right? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Unfortunately this isn't currently possible. Feel free to open a feature request with a proposed syntax. Essentially you'd somehow have to define |
Beta Was this translation helpful? Give feedback.
-
I recently tried to create something where this would have been quite useful: a higher-order function to take functions that throw exceptions, catch (and log) them, and then return a WP_Error object instead. /**
* Wraps a function so that, when run, any exceptions are caught, logged, and converted to a generic WP_Error.
*
* Works with functions of up to 5 parameters. (Add more PX generic types to this docblock to add support for more params.)
*
* @template P1
* @template P2
* @template P3
* @template P4
* @template P5
* @template R
*
* @param (Closure(P1, P2, P3, P4, P5): R) $fn Function that could throw.
*
* @return (Closure(P1, P2, P3, P4, P5): (R|WP_Error))
*/
function handleExceptionsAsWpErrors(Closure $fn, LoggerInterface $logger): Closure {
return static function (...$params) use ($fn, $logger) {
try {
return $fn(...$params);
} catch (Throwable $e) {
$logger->error($e->getMessage());
return new WP_Error('arn_internal_server_error');
}
};
} In this case, I was hoping that I could get around the issue of having variable numbers of params by hardcoding generics for a reasonable max number of parameters. My hope was that, that for Closures with less than 5 params, the unused Of course, it didn't actually work when I tried it, and I suspect that not even setting explicit defaults for the template types (once #1835 lands) would alter the behavior here. But should it work? Is a parameter of type It's also worth noting that TypeScript has a /**
* @template R
*
* @param (Closure(...): R) $fn
*
* @return (Closure(...parameters<$fn>): (R|WP_Error))
*/ What do you think of these ideas? |
Beta Was this translation helpful? Give feedback.
Unfortunately this isn't currently possible. Feel free to open a feature request with a proposed syntax. Essentially you'd somehow have to define
@template
dynamically for each callable argument, so that your case works in general: https://phpstan.org/r/84dfb636-f7b3-4746-b61b-5eb1a2f5a683