Skip to content

Generic annotations #23

Closed
Closed
@Radiergummi

Description

@Radiergummi

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions