Lines
100.00%
19 / 19
Functions and Methods
100.00%
3 / 3
Classes and Traits
100.00%
1 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| PlayerEnteredEvent | 100.00% | 19 / 19 | 100.00% | 3 / 3 | 8 | 100.00% | 1 / 1 | |||
| __construct | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| from | 100.00% | 17 / 17 | 100.00% | 1 / 1 | 6 | |||||
| summary | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Lorekeeper\Server\Event\Player; | |
| 6 | ||
| 7 | use DOMElement; | |
| 8 | use Lorekeeper\Core\Player\PlayerName; | |
| 9 | use Lorekeeper\Core\Player\PlayerSpawnId; | |
| 10 | use Lorekeeper\Server\Event\Event; | |
| 11 | use Lorekeeper\Server\Event\NamedAfterClass; | |
| 12 | use Lorekeeper\Server\Exception\MalformedEventException; | |
| 13 | use Lorekeeper\Server\Message\Message; | |
| 14 | use Lorekeeper\Server\Message\XmlMessage; | |
| 15 | use Override; | |
| 16 | use Psl\Option; | |
| 17 | use Psl\Type; | |
| 18 | use Psl\Type\Exception\CoercionException; | |
| 19 | ||
| 20 | /** | |
| 21 | * A player entered the room. | |
| 22 | */ | |
| 23 | final readonly class PlayerEnteredEvent implements Event | |
| 24 | { | |
| 25 | use NamedAfterClass; | |
| 26 | ||
| 27 | public function __construct( | |
| 28 | public PlayerSpawnId $spawnId, | |
| 29 | public PlayerName $name, | |
| 30 | ) {} | |
| 31 | ||
| 32 | /** @return Option\Option<static> */ | |
| 33 | #[Override] | |
| 34 | public static function from(Message $message): Option\Option | |
| 35 | { | |
| 36 | if (!$message instanceof XmlMessage) { | |
| 37 | return Option\none(); | |
| 38 | } | |
| 39 | ||
| 40 | $body = $message->dom->getElementsByTagName('body')->item(0); | |
| 41 | if (!$body instanceof DOMElement || $body->getAttribute('action') !== 'uER') { | |
| 42 | return Option\none(); | |
| 43 | } | |
| 44 | ||
| 45 | $user = $body->getElementsByTagName('u')->item(0); | |
| 46 | if (!$user instanceof DOMElement) { | |
| 47 | throw new MalformedEventException(static::class, 'the player is missing'); | |
| 48 | } | |
| 49 | ||
| 50 | try { | |
| 51 | $spawnId = Type\positive_int()->coerce($user->getAttribute('i')); | |
| 52 | $name = Type\non_empty_string()->coerce($user->getElementsByTagName('n')->item(0)?->textContent); | |
| 53 | } catch (CoercionException $exception) { | |
| 54 | throw new MalformedEventException( | |
| 55 | static::class, | |
| 56 | 'player spawn id or name is missing or invalid', | |
| 57 | $exception, | |
| 58 | ); | |
| 59 | } | |
| 60 | ||
| 61 | return Option\some(new static(new PlayerSpawnId($spawnId), new PlayerName($name))); | |
| 62 | } | |
| 63 | ||
| 64 | #[Override] | |
| 65 | public function summary(): string | |
| 66 | { | |
| 67 | return "{$this->name->value} (spawn {$this->spawnId->value}) entered"; | |
| 68 | } | |
| 69 | } |