File size: 1,125 Bytes
45dc401
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
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
41
42
<?php

declare(strict_types=1);

namespace App\Domain\Analytics;

final class AnalyticsSessionTransitioner
{
    private const ALLOWED = [
        'open' => ['closed'],
    ];

    public function __construct(private readonly AnalyticsSessionRepository $sessions) {}

    /**
     * Transition a session from open → closed.
     * Silently skips if the session does not exist (e.g. already expired / beacon race).
     *
     * @param  int  $durationSeconds  Wall-clock seconds from started_at to close; caller computes this.
     */
    public function close(string $sessionId, string $exitPath, int $durationSeconds): void
    {
        $session = $this->sessions->findById($sessionId);

        if ($session === null) {
            return;
        }

        $this->guard($session->status, 'closed');

        $this->sessions->close($sessionId, $exitPath, $durationSeconds);
    }

    private function guard(string $from, string $to): void
    {
        $allowed = self::ALLOWED[$from] ?? [];
        if (!in_array($to, $allowed, true)) {
            throw new InvalidTransitionException($from, $to);
        }
    }
}