Skip to content

Commit

Permalink
[3.x] Add template annotations
Browse files Browse the repository at this point in the history
Adds template annotations turning the `PromiseInterface` into a generic.

Variables `$p1` and `$p2` in the following code example both are `PromiseInterface<int|string>`.

```php
$f = function (): int|string {
    return time() % 2 ? 'string' : time();
};

/**
 * @return PromiseInterface<int|string>
 */
$fp = function (): PromiseInterface {
    return resolve(time() % 2 ? 'string' : time());
};

$p1 = resolve($f());
$p2 = $fp();
```

When calling `then` on `$p1` or `$p2`, PHPStan understand that function `$f1` is type hinting its parameter fine, but `$f2` will throw during runtime:

```php
$p2->then(static function (int|string $a) {});
$p2->then(static function (bool $a) {});
```

Builds on top of reactphp#246 and reactphp#188 and is a requirement for reactphp/async#40
  • Loading branch information
simPod authored and WyriHaximus committed Jul 11, 2023
1 parent d87b562 commit 1096398
Show file tree
Hide file tree
Showing 34 changed files with 375 additions and 43 deletions.
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/.gitattributes export-ignore
/.github/ export-ignore
/.gitignore export-ignore
/phpstan.legacy.neon.dist export-ignore
/phpstan.neon.dist export-ignore
/phpunit.xml.dist export-ignore
/phpunit.xml.legacy export-ignore
Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ jobs:
name: PHPStan (PHP ${{ matrix.php }})
runs-on: ubuntu-22.04
strategy:
fail-fast: false
matrix:
php:
- 8.2
Expand All @@ -52,3 +53,6 @@ jobs:
coverage: none
- run: composer install
- run: vendor/bin/phpstan
if: ${{ matrix.php >= 7.2 }}
- run: vendor/bin/phpstan --configuration="phpstan.legacy.neon.dist"
if: ${{ matrix.php < 7.2 }}
9 changes: 9 additions & 0 deletions phpstan.legacy.neon.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
parameters:
ignoreErrors:
- '#Template type T is declared as covariant, but occurs in contravariant position in parameter result of method React\\Promise\\Promise::settle\(\).#'
- '#Template type T is declared as covariant, but occurs in contravariant position in parameter promise of method React\\Promise\\Promise::unwrap\(\).#'
- '#PHPDoc tag @param has invalid value \(\?\(callable\(T\): \(Fulfilled\|void\)\) \$onFulfilled\): Unexpected token "\(", expected type at offset 1165#'
- '#Template type Fulfilled of method React\\Promise\\PromiseInterface::then\(\) is not referenced in a parameter.#'

includes:
- phpstan.neon.dist
12 changes: 10 additions & 2 deletions src/Deferred.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@

namespace React\Promise;

/**
* @template T
*/
final class Deferred
{
/** @var Promise */
/**
* @var PromiseInterface<T>
*/
private $promise;

/** @var callable */
Expand All @@ -21,13 +26,16 @@ public function __construct(callable $canceller = null)
}, $canceller);
}

/**
* @return PromiseInterface<T>
*/
public function promise(): PromiseInterface
{
return $this->promise;
}

/**
* @param mixed $value
* @param T $value
*/
public function resolve($value): void
{
Expand Down
18 changes: 15 additions & 3 deletions src/Internal/FulfilledPromise.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,17 @@

/**
* @internal
*
* @template-implements PromiseInterface<T>
* @template-covariant T
*/
final class FulfilledPromise implements PromiseInterface
{
/** @var mixed */
/** @var T */
private $value;

/**
* @param mixed $value
* @param T $value
* @throws \InvalidArgumentException
*/
public function __construct($value = null)
Expand All @@ -26,14 +29,23 @@ public function __construct($value = null)
$this->value = $value;
}

/**
* @template TFulfilled
* @param ?(callable((T is void ? null : T)): (PromiseInterface<TFulfilled>|TFulfilled)) $onFulfilled
* @return ($onFulfilled is null ? PromiseInterface<T> : PromiseInterface<TFulfilled>)
*/
public function then(callable $onFulfilled = null, callable $onRejected = null): PromiseInterface
{
if (null === $onFulfilled) {
return $this;
}

try {
return resolve($onFulfilled($this->value));
/**
* @var PromiseInterface<T>|T $result
*/
$result = $onFulfilled($this->value);
return resolve($result);
} catch (\Throwable $exception) {
return new RejectedPromise($exception);
}
Expand Down
8 changes: 8 additions & 0 deletions src/Internal/RejectedPromise.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@

/**
* @internal
*
* @template-implements PromiseInterface<never>
* @template-covariant T
*/
final class RejectedPromise implements PromiseInterface
{
Expand Down Expand Up @@ -37,6 +40,11 @@ public function __destruct()
\error_log($message);
}

/**
* @template TRejected
* @param ?(callable(\Throwable): (PromiseInterface<TRejected>|TRejected)) $onRejected
* @return ($onRejected is null ? PromiseInterface<T> : PromiseInterface<TRejected>)
*/
public function then(callable $onFulfilled = null, callable $onRejected = null): PromiseInterface
{
if (null === $onRejected) {
Expand Down
20 changes: 16 additions & 4 deletions src/Promise.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@

use React\Promise\Internal\RejectedPromise;

/**
* @template-implements PromiseInterface<T>
* @template-covariant T
*/
final class Promise implements PromiseInterface
{
/** @var ?callable */
private $canceller;

/** @var ?PromiseInterface */
/** @var ?PromiseInterface<T> */
private $result;

/** @var callable[] */
Expand Down Expand Up @@ -80,11 +84,11 @@ public function catch(callable $onRejected): PromiseInterface
public function finally(callable $onFulfilledOrRejected): PromiseInterface
{
return $this->then(static function ($value) use ($onFulfilledOrRejected) {
return resolve($onFulfilledOrRejected())->then(function () use ($value) {
return resolve($onFulfilledOrRejected())->then(static function () use ($value) {
return $value;
});
}, static function ($reason) use ($onFulfilledOrRejected) {
return resolve($onFulfilledOrRejected())->then(function () use ($reason) {
return resolve($onFulfilledOrRejected())->then(static function () use ($reason) {
return new RejectedPromise($reason);
});
});
Expand Down Expand Up @@ -175,6 +179,10 @@ private function reject(\Throwable $reason): void
$this->settle(reject($reason));
}

/**
* Test out if null can be promise
* @param PromiseInterface<T>|PromiseInterface<never> $result
*/
private function settle(PromiseInterface $result): void
{
$result = $this->unwrap($result);
Expand Down Expand Up @@ -207,13 +215,17 @@ private function settle(PromiseInterface $result): void
}
}

/**
* @param PromiseInterface<T>|PromiseInterface<never> $promise
* @return PromiseInterface<T>
*/
private function unwrap(PromiseInterface $promise): PromiseInterface
{
while ($promise instanceof self && null !== $promise->result) {
$promise = $promise->result;
}

return $promise;
return $promise; /** @phpstan-ignore-line */
}

private function call(callable $cb): void
Expand Down
29 changes: 20 additions & 9 deletions src/PromiseInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

namespace React\Promise;

/**
* @template-covariant T
*/
interface PromiseInterface
{
/**
Expand All @@ -28,9 +31,18 @@ interface PromiseInterface
* 2. `$onFulfilled` and `$onRejected` will never be called more
* than once.
*
* @param callable|null $onFulfilled
* @param callable|null $onRejected
* @return PromiseInterface
* @template TFulfilled
* @template TRejected
* @param ?(callable((T is void ? null : T)): (PromiseInterface<TFulfilled>|TFulfilled)) $onFulfilled
* @param ?(callable(\Throwable): (PromiseInterface<TRejected>|TRejected)) $onRejected
* @return ($onRejected is null ?
* ($onFulfilled is null ? PromiseInterface<T> : (
* PromiseInterface<(T is never ? T : TFulfilled)>
* )) :
* ($onFulfilled is null ? PromiseInterface<T|TRejected> : (
* PromiseInterface<(T is never ? TRejected : TFulfilled|TRejected)>
* ))
* )
*/
public function then(?callable $onFulfilled = null, ?callable $onRejected = null): PromiseInterface;

Expand All @@ -44,8 +56,7 @@ public function then(?callable $onFulfilled = null, ?callable $onRejected = null
* Additionally, you can type hint the `$reason` argument of `$onRejected` to catch
* only specific errors.
*
* @param callable $onRejected
* @return PromiseInterface
* @return PromiseInterface<T>
*/
public function catch(callable $onRejected): PromiseInterface;

Expand Down Expand Up @@ -91,8 +102,8 @@ public function catch(callable $onRejected): PromiseInterface;
* ->finally('cleanup');
* ```
*
* @param callable $onFulfilledOrRejected
* @return PromiseInterface
* @param callable(): (mixed|void) $onFulfilledOrRejected
* @return PromiseInterface<T>
*/
public function finally(callable $onFulfilledOrRejected): PromiseInterface;

Expand All @@ -118,7 +129,7 @@ public function cancel(): void;
* ```
*
* @param callable $onRejected
* @return PromiseInterface
* @return PromiseInterface<T>
* @deprecated 3.0.0 Use catch() instead
* @see self::catch()
*/
Expand All @@ -135,7 +146,7 @@ public function otherwise(callable $onRejected): PromiseInterface;
* ```
*
* @param callable $onFulfilledOrRejected
* @return PromiseInterface
* @return PromiseInterface<T>
* @deprecated 3.0.0 Use finally() instead
* @see self::finally()
*/
Expand Down
36 changes: 24 additions & 12 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@
*
* If `$promiseOrValue` is a promise, it will be returned as is.
*
* @param mixed $promiseOrValue
* @return PromiseInterface
* @template T
* @param PromiseInterface<T>|T $promiseOrValue
* @return PromiseInterface<T>
*/
function resolve($promiseOrValue): PromiseInterface
{
Expand All @@ -30,6 +31,7 @@ function resolve($promiseOrValue): PromiseInterface
$canceller = null;

if (\method_exists($promiseOrValue, 'cancel')) {
/** @var callable $canceller */
$canceller = [$promiseOrValue, 'cancel'];
}

Expand All @@ -54,8 +56,7 @@ function resolve($promiseOrValue): PromiseInterface
* throwing an exception. For example, it allows you to propagate a rejection with
* the value of another promise.
*
* @param \Throwable $reason
* @return PromiseInterface
* @return PromiseInterface<never>
*/
function reject(\Throwable $reason): PromiseInterface
{
Expand All @@ -68,8 +69,9 @@ function reject(\Throwable $reason): PromiseInterface
* will be an array containing the resolution values of each of the items in
* `$promisesOrValues`.
*
* @param iterable<mixed> $promisesOrValues
* @return PromiseInterface
* @template T
* @param iterable<PromiseInterface<T>|T> $promisesOrValues
* @return PromiseInterface<array<T>>
*/
function all(iterable $promisesOrValues): PromiseInterface
{
Expand All @@ -86,7 +88,11 @@ function all(iterable $promisesOrValues): PromiseInterface
$values[$i] = null;
++$toResolve;

resolve($promiseOrValue)->then(
/**
* @var PromiseInterface<T> $p
*/
$p = resolve($promiseOrValue);
$p->then(
function ($value) use ($i, &$values, &$toResolve, &$continue, $resolve): void {
$values[$i] = $value;

Expand Down Expand Up @@ -119,8 +125,9 @@ function (\Throwable $reason) use (&$continue, $reject): void {
* The returned promise will become **infinitely pending** if `$promisesOrValues`
* contains 0 items.
*
* @param iterable<mixed> $promisesOrValues
* @return PromiseInterface
* @template T
* @param iterable<PromiseInterface<T>|T> $promisesOrValues
* @return PromiseInterface<T>
*/
function race(iterable $promisesOrValues): PromiseInterface
{
Expand Down Expand Up @@ -154,8 +161,9 @@ function race(iterable $promisesOrValues): PromiseInterface
* The returned promise will also reject with a `React\Promise\Exception\LengthException`
* if `$promisesOrValues` contains 0 items.
*
* @param iterable<mixed> $promisesOrValues
* @return PromiseInterface
* @template T
* @param iterable<PromiseInterface<T>|T> $promisesOrValues
* @return PromiseInterface<T>
*/
function any(iterable $promisesOrValues): PromiseInterface
{
Expand All @@ -170,7 +178,11 @@ function any(iterable $promisesOrValues): PromiseInterface
$cancellationQueue->enqueue($promiseOrValue);
++$toReject;

resolve($promiseOrValue)->then(
/**
* @var PromiseInterface<T> $p
*/
$p = resolve($promiseOrValue);
$p->then(
function ($value) use ($resolve, &$continue): void {
$continue = false;
$resolve($value);
Expand Down
1 change: 0 additions & 1 deletion tests/DeferredTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ public function shouldRejectWithoutCreatingGarbageCyclesIfCancellerHoldsReferenc
gc_collect_cycles();
gc_collect_cycles(); // clear twice to avoid leftovers in PHP 7.4 with ext-xdebug and code coverage turned on

/** @var Deferred $deferred */
$deferred = new Deferred(function () use (&$deferred) {
assert($deferred instanceof Deferred);
});
Expand Down
1 change: 1 addition & 0 deletions tests/FunctionAnyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public function shouldResolveWithAnInputValue(): void
->expects(self::once())
->method('__invoke')
->with(self::identicalTo(1));
assert(is_callable($mock));

any([1, 2, 3])
->then($mock);
Expand Down
4 changes: 3 additions & 1 deletion tests/FunctionResolveTestThenShouldNotReportUnhandled.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ use function React\Promise\resolve;

require __DIR__ . '/../vendor/autoload.php';

resolve(42)->then('var_dump');
/** @var callable $callable */
$callable = 'var_dump';
resolve(42)->then($callable);

?>
--EXPECT--
Expand Down
3 changes: 3 additions & 0 deletions tests/Internal/CancellationQueueTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,9 @@ public function rethrowsExceptionsThrownFromCancel(): void
$cancellationQueue();
}

/**
* @return Deferred<never>
*/
private function getCancellableDeferred(): Deferred
{
return new Deferred($this->expectCallableOnce());
Expand Down
Loading

0 comments on commit 1096398

Please sign in to comment.