. * * @author Daniil Gentili * @copyright 2016-2020 Daniil Gentili * @license https://opensource.org/licenses/AGPL-3.0 AGPLv3 * * @link https://docs.madelineproto.xyz MadelineProto documentation */ namespace danog\MadelineProto\Loop\Impl; use Amp\Promise; use danog\MadelineProto\Logger; use danog\MadelineProto\Loop\LoopInterface; /** * Loop helper trait. * * Wraps the asynchronous generator methods with asynchronous promise-based methods * * @author Daniil Gentili */ abstract class Loop implements LoopInterface { private $count = 0; /** * MTProto instance. * * @var \danog\MadelineProto\MTProto */ public $API; public function __construct($API) { $this->API = $API; } public function start() { if ($this->count) { //$this->API->logger->logger("NOT entering $this with running count {$this->count}", Logger::ERROR); return false; } return \danog\MadelineProto\Tools::callFork($this->loopImpl()); } private function loopImpl(): \Generator { $this->startedLoop(); $this->API->logger->logger("Entered {$this}", Logger::ULTRA_VERBOSE); try { yield from $this->loop(); } finally { $this->exitedLoop(); $this->API->logger->logger("Physically exited {$this}", Logger::ULTRA_VERBOSE); } } public function exitedLoop() { if ($this->count) { $this->API->logger->logger("Exited {$this}", Logger::ULTRA_VERBOSE); $this->count--; } } public function startedLoop() { $this->count++; } public function isRunning() { return $this->count; } }