Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
20 / 20 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| InviteMemberHandler | |
100.00% |
20 / 20 |
|
100.00% |
2 / 2 |
7 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| handle | |
100.00% |
19 / 19 |
|
100.00% |
1 / 1 |
6 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace App\Trip\Application\Command; |
| 6 | |
| 7 | use App\Trip\Application\Port\MemberDirectory; |
| 8 | use App\Trip\Application\TripAccess; |
| 9 | use App\Trip\Domain\Exceptions\AlreadyMemberOrInvited; |
| 10 | use App\Trip\Domain\Exceptions\InviteeNotFound; |
| 11 | use App\Trip\Domain\TripInvitation; |
| 12 | use App\Trip\Domain\TripInvitationRepository; |
| 13 | use App\Trip\Domain\TripMemberRepository; |
| 14 | use App\Trip\Domain\ValueObject\InvitationId; |
| 15 | use App\Trip\Domain\ValueObject\MemberId; |
| 16 | use App\Trip\Domain\ValueObject\OwnerId; |
| 17 | use App\Trip\Domain\ValueObject\TripId; |
| 18 | use App\Trip\Domain\ValueObject\TripRole; |
| 19 | use InvalidArgumentException; |
| 20 | |
| 21 | final readonly class InviteMemberHandler |
| 22 | { |
| 23 | public function __construct( |
| 24 | private TripAccess $access, |
| 25 | private MemberDirectory $directory, |
| 26 | private TripMemberRepository $members, |
| 27 | private TripInvitationRepository $invitations, |
| 28 | ) { |
| 29 | } |
| 30 | |
| 31 | public function handle(InviteMemberCommand $command): InvitationId |
| 32 | { |
| 33 | // Owner-only: stranger -> TripNotFound (404), non-owner member -> TripAccessDenied (403). |
| 34 | $trip = $this->access->getForManage(new TripId($command->tripId), $command->inviterUserId); |
| 35 | |
| 36 | $role = TripRole::tryFrom($command->role); |
| 37 | if ($role === null || !$role->isStorableMembership()) { |
| 38 | throw new InvalidArgumentException('Role must be editor or viewer.'); |
| 39 | } |
| 40 | |
| 41 | $inviteeId = $this->directory->findIdByEmail($command->email) |
| 42 | ?? throw InviteeNotFound::withEmail($command->email); |
| 43 | |
| 44 | $alreadyOwner = $trip->isOwnedBy(new OwnerId($inviteeId->value())); |
| 45 | $alreadyMember = $this->members->roleOf($trip->id(), $inviteeId) !== null; |
| 46 | $alreadyInvited = $this->invitations->pendingFor($trip->id(), $inviteeId) !== null; |
| 47 | |
| 48 | if ($alreadyOwner || $alreadyMember || $alreadyInvited) { |
| 49 | throw AlreadyMemberOrInvited::create(); |
| 50 | } |
| 51 | |
| 52 | $invitation = TripInvitation::invite( |
| 53 | $trip->id(), |
| 54 | $inviteeId, |
| 55 | new MemberId($command->inviterUserId), |
| 56 | $role, |
| 57 | ); |
| 58 | $this->invitations->save($invitation); |
| 59 | |
| 60 | return $invitation->id(); |
| 61 | } |
| 62 | } |