Converts a Promise to an Observable sequence

@param PromiseInterface $promise
@return Observable
@throws \InvalidArgumentException
979467
public static function toObservable(PromiseInterface $promise): Observable
    {
        $subject = new AsyncSubject();

        $p = $promise->then(
            function ($value) use ($subject) {
                $subject->onNext($value);
                $subject->onCompleted();
            },
            function ($error) use ($subject) {
                $error = $error instanceof \Exception ? $error : new RejectedPromiseException($error);
                $subject->onError($error);
            }
        );

        return new AnonymousObservable(function ($observer) use ($subject, $p) {
            $disp = $subject->subscribe($observer);
            return new CallbackDisposable(function () use ($p, $disp) {
                $disp->dispose();
                if ($p instanceof CancellablePromiseInterface) {
                    $p->cancel();
                }
            });
        });
    }
843902
public function serialize(EventInterface $event)
    {
        if (!$event instanceof \JsonSerializable) {
            throw new \InvalidArgumentException(sprintf('Cannot serialize %s event.', $event->getName()));
        }

        return json_encode($event);
    }
1270348
public function sendAsync(): Promise
	{
		$mappedParams = $this->map();

		$curler = new \GuzzleHttp\Client(['base_uri' => $this->tgUrl]);

		if (empty($this->multipart)) {
			$promise = $curler->requestAsync("POST", static::$method, [
				"query" => $mappedParams
			]);
		} else {
			$promise = $curler->requestAsync("POST", static::$method, [
				"query" => $mappedParams,
				"multipart" => $this->multipart
			]);
		}

		$processedPromise = $promise->then(function ($response) {
			$jsonResponse = json_decode((string)$response->getBody(), true);
			$result = $jsonResponse['result'];
			return static::decodeResult($result);
		});

		$this->bot->addPromise($processedPromise);
		return $processedPromise;
	}
251143
private function createPromiseForPush(PushInterface $push, RecipientInterface $recipient): PromiseInterface {
        return $this->client->sendAsync($this->prepareRequest($push->getMessage(), $recipient))
            ->otherwise(function (\Exception $exception) use ($push, $recipient) {
                $push->setFailedFor($recipient, $exception);
            });
    }
247166
protected function send(PromiseInterface $promise)
    {
        $pid     = $this->protocol->getPid();
        $origin  = $this->protocol->getOrigin();
        $message = $this->message;
        $channel = $this->channel;

        if ($message instanceof Error || $message instanceof Exception)
        {
            $answer = $channel
                ->createProtocol($message->getMessage())
                ->setPid($pid, true)
                ->setException(get_class($message), true)
            ;
        }
        else
        {
            $answer = $channel
                ->createProtocol($message)
                ->setPid($pid, true)
            ;
        }

        $this->channel->send(
            $origin,
            $answer,
            Channel::MODE_BUFFER_ONLINE
        );

        return $promise->resolve();
    }
182115
public function subscribe(Subscription $subscription)
    {
        if (!$this->isConnected) {
            return new RejectedPromise(new \LogicException('The client is not connected.'));
        }

        return $this->startFlow(new OutgoingSubscribeFlow([$subscription], $this->identifierGenerator));
    }
921028
public function preparePersistChangeSet($object) : array
    {
        if (! $object instanceof PersistableInterface) {
            throw new InvalidArgumentException(
                sprintf('%s must implement PersistableInterface.', get_class($object))
            );
        }

        return $object->preparePersistChangeSet();
    }
323342
public function dispatch($query): PromiseInterface
    {
        $deferred = new Deferred();

        $actionEventEmitter = $this->events;

        $actionEvent = $actionEventEmitter->getNewActionEvent(
            self::EVENT_DISPATCH,
            $this,
            [
                self::EVENT_PARAM_MESSAGE => $query,
                self::EVENT_PARAM_DEFERRED => $deferred,
                self::EVENT_PARAM_PROMISE => $deferred->promise(),
            ]
        );

        try {
            $actionEventEmitter->dispatch($actionEvent);

            if (! $actionEvent->getParam(self::EVENT_PARAM_MESSAGE_HANDLED)) {
                throw new RuntimeException(\sprintf('Query %s was not handled', $this->getMessageName($query)));
            }
        } catch (\Throwable $exception) {
            $actionEvent->setParam(self::EVENT_PARAM_EXCEPTION, $exception);
        } finally {
            $actionEvent->stopPropagation(false);
            $this->triggerFinalize($actionEvent);
        }

        return $actionEvent->getParam(self::EVENT_PARAM_PROMISE);
    }
908460
protected static function chainApply(&$promise, $chain = [])
    {
        foreach ($chain as $row) {
            $promise = call_user_func_array([$promise, $row['method']], $row['arguments']);
        }
    }
908097
protected function initPromises($promisesTrait)
    {
        return $promisesTrait->findOne($this->createFindOneClosure())
            ->findMany($this->createFindManyClosure())
            ->renderResult($this->createRenderResultClosure())
            ->allowRequest($this->createAllowRequestClosure());
    }
1367228
protected function onFailure(RequestInterface $request)
    {
        return function ($reason) use ($request) {
            if ($this->enabled) {
                $response = null;

                if ($reason instanceof RequestException) {
                    $response = $reason->getResponse();
                }

                $this->log($request, $response);
            }

            return Promise\rejection_for($reason);
        };
    }
1231770
public function wait(Promise $promise, callable $onProgress = null): ?ExecutionResult
    {
        if (!$this->isThenable($promise)) {
            throw new \InvalidArgumentException(\sprintf('The "%s" method must be call with compatible a Promise.', __METHOD__));
        }
        $wait = true;
        $resolvedValue = null;
        $exception = null;
        /** @var \React\Promise\PromiseInterface $reactPromise */
        $reactPromise = $promise->adoptedPromise;

        $reactPromise->then(function ($values) use (&$resolvedValue, &$wait): void {
            $resolvedValue = $values;
            $wait = false;
        }, function ($reason) use (&$exception, &$wait): void {
            $exception = $reason;
            $wait = false;
        });

        // wait until promise resolution
        while ($wait) {
            if (null !== $onProgress) {
                $onProgress();
            }
            // less CPU intensive without sacrificing the performance
            \usleep(5);
        }

        /** @var \Exception|null $exception */
        if (null !== $exception) {
            throw $exception;
        }

        return $resolvedValue;
    }
714701
public function reject(Throwable $reason)
    {
        if (self::PENDING !== $this->state) {
            throw new PromiseAlreadyResolvedException('This promise is already resolved, and you\'re not allowed to resolve a promise more than once');
        }
        $this->state = self::REJECTED;
        $this->value = $reason;
        foreach ($this->subscribers as $subscriber) {
            $this->invokeCallback($subscriber[0], $subscriber[2]);
        }
    }
1313451
public static function createAll($promisesOrValues)
    {
        $promise = empty($promisesOrValues) ? static::createResolve($promisesOrValues) : \GuzzleHttp\Promise\all($promisesOrValues);

        return $promise;
    }
149866
public static function fromResponse(ResponseInterface $response)
    {
        $name = $response->getHeaderLine('X-Endpoint');
        
        if (! isset(BaseApi::$endpointDefinitions[$name])) {
            throw new \InvalidArgumentException('Could not resolve Endpoint from the provided response: \n'.$response->getBody()->__toString());
        }

        /** @var BaseEndpoint $endpointClass */
        $endpointClass = BaseApi::$endpointDefinitions[$name]['class'];

        return new $endpointClass(Region::create($response->getHeaderLine('X-Region')));
    }
65620
public function getMessageSequence(string $sequence): MessageIteratorInterface
    {
        \imap_errors();

        $overview = \imap_fetch_overview($this->resource->getStream(), $sequence, \FT_UID);
        if (\is_array($overview) && [] !== $overview) {
            $messageNumbers = \array_column($overview, 'uid');
        } else {
            if (false !== \imap_last_error()) {
                throw new InvalidSearchCriteriaException(\sprintf('Invalid sequence [%s]', $sequence));
            }

            $messageNumbers = [];
        }

        return new MessageIterator($this->resource, $messageNumbers);
    }
81236
function setMessageObject(ResponseInterface $httpMessage)
    {
        if (!$httpMessage instanceof ResponseInterface)
            throw new \InvalidArgumentException(sprintf(
                'This plugin need response object instance of iHttpResponse, "%s" given.'
                , get_class($httpMessage)
            ));

        $this->messageObject = $httpMessage;
        return $this;
    }