DoorCommandHandler.php 987 Bytes
Newer Older
1
2
3
4
5
<?php


namespace Source\UseCases\Door\Commands;

Jacob Priddy's avatar
Jacob Priddy committed
6
7
8
use Source\Entities\User;

class DoorCommandHandler implements CommandHandler
9
{
Jacob Priddy's avatar
Jacob Priddy committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    /**
     * @var \Source\UseCases\Door\Commands\Command[]
     */
    protected array $commands = [];

    public function __construct(Command ...$commands)
    {
        foreach ($commands as $command) {
            $this->commands[$command->getOpcode()] = $command;
        }
    }

    /**
     * @inheritDoc
     */
    public function handle(User $user, string $doorId, string $commandString): bool
    {
        // Need to be able to parse OPCode
        if (strlen($commandString) < 2) {
            return false;
        }

        // First 2 digits are the command opcode
        $opcode = substr($commandString, 0, 2);
        $args = substr($commandString, 2);

        $command = $this->commands[$opcode] ?? null;

        if (!$command) {
            return false;
        }
41

Jacob Priddy's avatar
Jacob Priddy committed
42
43
        return $command->execute($user, $doorId, $args);
    }
44
}