laravel-websockets/tests/Mocks/PromiseResolver.php

75 lines
1.8 KiB
PHP
Raw Normal View History

<?php
2025-01-16 07:54:02 +00:00
namespace BlaxSoftware\LaravelWebSockets\Test\Mocks;
2025-01-16 07:54:02 +00:00
use BlaxSoftware\LaravelWebSockets\Helpers;
use Clue\React\Block;
2020-09-19 11:16:26 +00:00
use React\EventLoop\LoopInterface;
2020-09-10 19:59:26 +00:00
use React\Promise\FulfilledPromise;
2020-09-10 19:59:49 +00:00
use React\Promise\PromiseInterface;
class PromiseResolver implements PromiseInterface
{
/**
* The promise to resolve.
*
* @var \React\Promise\PromiseInterface
*/
protected $promise;
/**
* The loop.
*
* @var \React\EventLoop\LoopInterface
*/
protected $loop;
/**
* Initialize the promise resolver.
*
2020-09-19 11:16:26 +00:00
* @param mixed $promise
* @param LoopInterface $loop
* @return void
*/
2020-09-19 11:16:26 +00:00
public function __construct($promise, LoopInterface $loop)
{
2020-09-19 11:16:26 +00:00
$this->promise = $promise instanceof PromiseInterface ? $promise : new FulfilledPromise($promise);
$this->loop = $loop;
}
/**
* Intercept the promise then() and run it in sync.
*
* @param callable|null $onFulfilled
* @param callable|null $onRejected
* @param callable|null $onProgress
* @return PromiseInterface
*/
public function then(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null)
{
$result = Block\await(
$this->promise, $this->loop
);
2026-03-21 11:56:50 +00:00
if ($onFulfilled !== null) {
$result = call_user_func($onFulfilled, $result);
}
2020-09-10 19:59:26 +00:00
return $result instanceof PromiseInterface
? new self($result, $this->loop)
2020-09-19 11:16:26 +00:00
: new self(Helpers::createFulfilledPromise($result), $this->loop);
}
/**
* Pass the calls to the promise.
*
* @param string $method
* @param array $args
* @return mixed
*/
public function __call($method, $args)
{
return call_user_func([$this->promise, $method], $args);
}
}