Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.91% covered (success)
90.91%
20 / 22
75.00% covered (warning)
75.00%
3 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
SequenceScript
90.91% covered (success)
90.91%
20 / 22
75.00% covered (warning)
75.00%
3 / 4
10.08
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 start
50.00% covered (danger)
50.00%
2 / 4
0.00% covered (danger)
0.00%
0 / 1
2.50
 handles
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 handle
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
6
1<?php
2
3declare(strict_types=1);
4
5namespace AqwSocketClient\Scripts;
6
7use AqwSocketClient\Enums\ScriptResult;
8use AqwSocketClient\Interfaces\CommandInterface;
9use AqwSocketClient\Interfaces\EventInterface;
10use AqwSocketClient\Interfaces\ExpirableScriptInterface;
11use AqwSocketClient\Interfaces\ScriptInterface;
12use Override;
13
14/**
15 * Runs a list of scripts in order.
16 *
17 * Advances to the next script when the current one completes with Success.
18 * Fails immediately if any child fails, disconnects, or expires.
19 */
20class SequenceScript extends AbstractScript
21{
22    private int $current = 0;
23
24    /**
25     * @param ScriptInterface[] $scripts
26     */
27    public function __construct(
28        private readonly array $scripts,
29    ) {}
30
31    #[Override]
32    public function start(ClientContext $context): ?CommandInterface
33    {
34        if ($this->scripts === []) {
35            $this->success();
36            return null;
37        }
38
39        return $this->scripts[0]->start($context);
40    }
41
42    #[Override]
43    public function handles(): array
44    {
45        return $this->scripts[$this->current]->handles();
46    }
47
48    #[Override]
49    public function handle(EventInterface $event, ClientContext $context): ?CommandInterface
50    {
51        $child = $this->scripts[$this->current];
52
53        if ($child instanceof ExpirableScriptInterface && $child->isExpired()) {
54            $child->expired();
55            $this->failed();
56            return null;
57        }
58
59        $command = $child->handle($event, $context);
60
61        if ($child->isDone()) {
62            if ($child->result() !== ScriptResult::Success) {
63                $this->failed();
64                return null;
65            }
66
67            $this->current++;
68
69            if ($this->current >= count($this->scripts)) {
70                $this->success();
71                return null;
72            }
73
74            return $this->scripts[$this->current]->start($context);
75        }
76
77        return $command;
78    }
79}