Lines 100.00% 14 / 14
Functions and Methods 100.00% 1 / 1
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
Paces 100.00% 14 / 14 100.00% 1 / 1 7 100.00% 1 / 1
 paced 100.00% 14 / 14 100.00% 1 / 1 7
1<?php
2
3declare(strict_types=1);
4
5namespace Lorekeeper\Bot\Abilities;
6
7use Generator;
8use Lorekeeper\Client\Script\Await;
9use Lorekeeper\Client\Script\Instruction;
10use Lorekeeper\Client\Script\Pause;
11use Lorekeeper\Client\Script\Send;
12use Lorekeeper\Client\Script\TimedOut;
13use Lorekeeper\Server\Event\ActionTooSoonEvent;
14use Lorekeeper\Server\Event\Event;
15use Lorekeeper\Server\Event\TooSoonAfterCombatEvent;
16use Psl\DateTime\Duration;
17
18trait Paces
19{
20    private const int TRIES_WHEN_TOO_SOON = 4;
21
22    /** @return Generator<int, Instruction, null|Event|TimedOut, null|Event|TimedOut> */
23    protected function paced(Send $send): Generator
24    {
25        $await = $send->await;
26        if ($await === null) {
27            return yield $send;
28        }
29
30        $watching = new Send($send->command, new Await([
31            ...$await->events,
32            ActionTooSoonEvent::class,
33            TooSoonAfterCombatEvent::class,
34        ], $await->timeout));
35        for ($try = 1;; $try++) {
36            $answer = yield $watching;
37            $tooSoon = $answer instanceof ActionTooSoonEvent || $answer instanceof TooSoonAfterCombatEvent;
38            if (!$tooSoon || $try >= self::TRIES_WHEN_TOO_SOON) {
39                return $answer;
40            }
41
42            yield new Pause(Duration::seconds($answer instanceof TooSoonAfterCombatEvent ? 2 : 1));
43        }
44    }
45}