|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Backslash\Event; |
| 6 | + |
| 7 | +use PHPUnit\Framework\Attributes\Test; |
| 8 | +use PHPUnit\Framework\TestCase; |
| 9 | +use RuntimeException; |
| 10 | + |
| 11 | +class ToArrayTraitTest extends TestCase |
| 12 | +{ |
| 13 | + #[Test] |
| 14 | + public function fromArray_with_variadic_parameter(): void |
| 15 | + { |
| 16 | + $event = VariadicEvent::fromArray([ |
| 17 | + 'teamId' => 'team-1', |
| 18 | + 'userIds' => ['user-1', 'user-2', 'user-3'], |
| 19 | + ]); |
| 20 | + |
| 21 | + $this->assertInstanceOf(VariadicEvent::class, $event); |
| 22 | + $this->assertSame('team-1', $event->teamId); |
| 23 | + $this->assertSame(['user-1', 'user-2', 'user-3'], $event->userIds); |
| 24 | + } |
| 25 | + |
| 26 | + #[Test] |
| 27 | + public function fromArray_with_empty_variadic_parameter(): void |
| 28 | + { |
| 29 | + $event = VariadicEvent::fromArray([ |
| 30 | + 'teamId' => 'team-1', |
| 31 | + 'userIds' => [], |
| 32 | + ]); |
| 33 | + |
| 34 | + $this->assertSame('team-1', $event->teamId); |
| 35 | + $this->assertSame([], $event->userIds); |
| 36 | + } |
| 37 | + |
| 38 | + #[Test] |
| 39 | + public function toArray_and_fromArray_roundtrip_with_variadic(): void |
| 40 | + { |
| 41 | + $original = new VariadicEvent('team-1', 'user-1', 'user-2'); |
| 42 | + $data = $original->toArray(); |
| 43 | + $restored = VariadicEvent::fromArray($data); |
| 44 | + |
| 45 | + $this->assertSame($original->teamId, $restored->teamId); |
| 46 | + $this->assertSame($original->userIds, $restored->userIds); |
| 47 | + } |
| 48 | + |
| 49 | + #[Test] |
| 50 | + public function fromArray_ignores_extra_keys(): void |
| 51 | + { |
| 52 | + $event = VariadicEvent::fromArray([ |
| 53 | + 'teamId' => 'team-1', |
| 54 | + 'userIds' => ['user-1'], |
| 55 | + 'removedAttribute' => 'should be ignored', |
| 56 | + ]); |
| 57 | + |
| 58 | + $this->assertSame('team-1', $event->teamId); |
| 59 | + $this->assertSame(['user-1'], $event->userIds); |
| 60 | + } |
| 61 | + |
| 62 | + #[Test] |
| 63 | + public function fromArray_throws_when_required_parameter_is_missing(): void |
| 64 | + { |
| 65 | + $this->expectException(RuntimeException::class); |
| 66 | + |
| 67 | + VariadicEvent::fromArray([ |
| 68 | + 'userIds' => ['user-1'], |
| 69 | + ]); |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +class VariadicEvent implements EventInterface |
| 74 | +{ |
| 75 | + use ToArrayTrait; |
| 76 | + |
| 77 | + public readonly array $userIds; |
| 78 | + |
| 79 | + public function __construct( |
| 80 | + public readonly string $teamId, |
| 81 | + string ...$userIds, |
| 82 | + ) { |
| 83 | + $this->userIds = $userIds; |
| 84 | + } |
| 85 | + |
| 86 | + public function getIdentifiers(): Identifiers |
| 87 | + { |
| 88 | + return new Identifiers(['teamId' => $this->teamId]); |
| 89 | + } |
| 90 | +} |
0 commit comments