ChatMessageRepository.php

Code Hygiene Score: 100

Keine Issues gefunden.

Dependencies 5

Klassen 1

Funktionen 7

Verwendet von 1

Versionen 8

Code

<?php

declare(strict_types=1);

namespace Infrastructure\Persistence;

// @responsibility: Persistenz für Chat-Nachrichten (CRUD, Session-Filter)

use Domain\Entity\ChatMessage;
use Domain\Factory\ChatMessageFactory;
use Domain\Repository\ChatMessageRepositoryInterface;

class ChatMessageRepository implements ChatMessageRepositoryInterface
{
    private \PDO $pdo;

    public function __construct(\PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function findBySessionId(int $sessionId): array
    {
        $stmt = $this->pdo->prepare(
            'SELECT * FROM chat_messages WHERE session_id = ? ORDER BY created_at ASC'
        );
        $stmt->execute([$sessionId]);

        $messages = [];
        foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
            $messages[] = ChatMessageFactory::fromArray($row);
        }

        return $messages;
    }

    public function saveEntity(ChatMessage $message): int
    {
        $data = $message->toArray();
        unset($data['id']);

        $stmt = $this->pdo->prepare(
            'INSERT INTO chat_messages
             (session_id, role, content, model, tokens_input, tokens_output, sources,
              start_microtime, end_microtime, author_profile_id, system_prompt_id, collections, context_limit, chunks_used, llm_request_id)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
        );
        $stmt->execute([
            $data['session_id'],
            $data['role'],
            $data['content'],
            $data['model'],
            $data['tokens_input'],
            $data['tokens_output'],
            $data['sources'],
            $data['start_microtime'],
            $data['end_microtime'],
            $data['author_profile_id'],
            $data['system_prompt_id'],
            $data['collections'],
            $data['context_limit'],
            $data['chunks_used'],
            $data['llm_request_id'],
        ]);

        // Update session timestamp
        $this->pdo->prepare('UPDATE chat_sessions SET updated_at = NOW() WHERE id = ?')
            ->execute([$message->sessionId()]);

        return (int) $this->pdo->lastInsertId();
    }

    public function save(
        int $sessionId,
        string $role,
        string $content,
        string $model,
        ?int $tokensInput = null,
        ?int $tokensOutput = null,
        ?array $sources = null,
        ?float $startMicrotime = null,
        ?float $endMicrotime = null,
        ?int $authorProfileId = null,
        ?int $systemPromptId = null,
        ?string $collectionsJson = null,
        ?int $contextLimit = null,
        ?int $llmRequestId = null
    ): int {
        $stmt = $this->pdo->prepare(
            'INSERT INTO chat_messages
             (session_id, role, content, model, tokens_input, tokens_output, sources,
              start_microtime, end_microtime, author_profile_id, system_prompt_id, collections, context_limit, llm_request_id)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
        );
        $stmt->execute([
            $sessionId,
            $role,
            $content,
            $model,
            $tokensInput,
            $tokensOutput,
            $sources !== null ? json_encode($sources) : null,
            $startMicrotime,
            $endMicrotime,
            $authorProfileId,
            $systemPromptId,
            $collectionsJson,
            $contextLimit,
            $llmRequestId,
        ]);

        // Update session timestamp
        $this->pdo->prepare('UPDATE chat_sessions SET updated_at = NOW() WHERE id = ?')
            ->execute([$sessionId]);

        return (int) $this->pdo->lastInsertId();
    }

    public function delete(int $id): void
    {
        $stmt = $this->pdo->prepare('DELETE FROM chat_messages WHERE id = ?');
        $stmt->execute([$id]);
    }

    public function deleteBySessionId(int $sessionId): void
    {
        $stmt = $this->pdo->prepare('DELETE FROM chat_messages WHERE session_id = ?');
        $stmt->execute([$sessionId]);
    }

    public function getSessionStats(int $sessionId): array
    {
        $stmt = $this->pdo->prepare(
            'SELECT
                COUNT(*) as message_count,
                COALESCE(SUM(tokens_input), 0) as total_input_tokens,
                COALESCE(SUM(tokens_output), 0) as total_output_tokens,
                COALESCE(SUM(end_microtime - start_microtime), 0) as total_duration
             FROM chat_messages
             WHERE session_id = ?'
        );
        $stmt->execute([$sessionId]);

        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }
}
← Übersicht Graph