MadelineProto/src/danog/MadelineProto/Async/AsyncConstruct.php

103 lines
2.7 KiB
PHP
Raw Normal View History

<?php
2020-01-31 19:29:43 +01:00
/**
* Async constructor abstract class.
*
* This file is part of MadelineProto.
* MadelineProto is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
* MadelineProto is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU General Public License along with MadelineProto.
* If not, see <http://www.gnu.org/licenses/>.
*
* @author Daniil Gentili <daniil@daniil.it>
2020-02-17 14:13:46 +01:00
* @copyright 2016-2020 Daniil Gentili <daniil@daniil.it>
* @license https://opensource.org/licenses/AGPL-3.0 AGPLv3
*
2019-10-31 15:07:35 +01:00
* @link https://docs.madelineproto.xyz MadelineProto documentation
*/
namespace danog\MadelineProto\Async;
2020-03-08 17:24:31 +01:00
use Amp\Promise;
use danog\MadelineProto\Tools;
/**
* Async constructor class.
*
* Manages asynchronous construction and wakeup of classes
*
* @author Daniil Gentili <daniil@daniil.it>
*/
class AsyncConstruct
{
2019-12-28 17:34:04 +01:00
/**
* Async init promise.
*
2020-09-27 19:36:17 +02:00
* @var Promise|null|boolean
2019-12-28 17:34:04 +01:00
*/
private $asyncInitPromise;
2019-12-28 17:34:04 +01:00
/**
* Blockingly init.
*
* @return void
*/
public function init(): void
{
if ($this->asyncInitPromise) {
2019-09-02 17:21:20 +02:00
Tools::wait($this->asyncInitPromise);
}
}
2019-12-28 17:34:04 +01:00
/**
* Asynchronously init.
*
* @return \Generator
*/
public function initAsynchronously(): \Generator
{
if ($this->asyncInitPromise) {
yield $this->asyncInitPromise;
}
}
/**
* Check if we've already inited.
*
* @return boolean
*/
public function inited(): bool
{
return !$this->asyncInitPromise;
}
/**
2020-02-26 11:47:30 +01:00
* Mark instance as (de)inited forcefully.
*
* @param boolean $inited Whether to mark the instance as inited or deinited
2020-02-26 11:47:30 +01:00
*
* @return void
*/
public function forceInit(bool $inited): void
{
$this->asyncInitPromise = $inited ? null : true;
}
2019-12-28 17:34:04 +01:00
/**
* Set init promise.
*
* @param Promise|\Generator $promise Promise
2019-12-28 17:34:04 +01:00
*
* @internal
*
* @return void
*/
public function setInitPromise($promise): void
{
$this->asyncInitPromise = Tools::call($promise);
$this->asyncInitPromise->onResolve(
function (?\Throwable $error, $result): void {
2020-09-27 19:36:17 +02:00
if (!$error) {
$this->asyncInitPromise = null;
}
}
);
}
}