Description
Description
By adding simple generic annotations to the PHPDoc comments of the Promise interface, it could gain a lot of introspection abilities. Even Laravel recently implemented generic annotations, so I guess you can call them widely supported and considered useful!
The neat thing about annotated generics in PHP is that they are entirely optional. So this would not cause any backwards-incompatibility to speak of.
Example
By adding an @template T
annotation to the main Promise
interface, and augmenting the type of then
with it, a Promise instance could be assigned a new meta property during static analysis: The value it will resolve to.
class PromiseFactory
{
/**
* @template T
* @param T $value
* @return Promise<T>
*/
public static function make(mixed $value): Promise {
return new SomePromiseImplementation($value);
}
}
/**
* @return Promise<string>
*/
function foo(): Promise {
return PromiseFactory::make('test');
}
// Inferred to be a string
$stringValue = foo()->wait();
Additional context
I originally hit this issue when upgrading the Elasticsearch dependency in our Laravel client from 7 to 8; in that version, the client may return a response instance or a promise, if async handling is enabled.
My original plan was to add support for promises too, so the client will either perform response handling synchronously if a Response instance is returned, or do the handling inside a then
callback; the client is really dependent on proper types, though, so as soon as I introduce promise support, I loose all the static analysis goodness the entire library provides.