TokenCount.php

Code Hygiene Score: 94

Keine Issues gefunden.

Dependencies 1

Klassen 1

Funktionen 13

Verwendet von 6

Code

<?php

declare(strict_types=1);

namespace Domain\ValueObject;

// @responsibility: Immutables Value Object für Token-Zählung (Input/Output)

use InvalidArgumentException;

final class TokenCount
{
    private int $input;
    private int $output;

    private function __construct(int $input, int $output)
    {
        $this->input = $input;
        $this->output = $output;
    }

    /**
     * Create from input and output counts.
     *
     * @throws InvalidArgumentException
     */
    public static function create(int $input, int $output): self
    {
        if ($input < 0) {
            throw new InvalidArgumentException('Input token count cannot be negative');
        }

        if ($output < 0) {
            throw new InvalidArgumentException('Output token count cannot be negative');
        }

        return new self($input, $output);
    }

    /**
     * Create from nullable values (for database rows).
     */
    public static function fromNullable(?int $input, ?int $output): self
    {
        return new self($input ?? 0, $output ?? 0);
    }

    /**
     * Create zero token count.
     */
    public static function zero(): self
    {
        return new self(0, 0);
    }

    public function input(): int
    {
        return $this->input;
    }

    public function output(): int
    {
        return $this->output;
    }

    public function total(): int
    {
        return $this->input + $this->output;
    }

    /**
     * Calculate estimated cost in USD based on Claude pricing.
     * Input: $15/1M tokens, Output: $75/1M tokens
     */
    public function estimatedCostUsd(): float
    {
        $inputCost = $this->input * 0.000015;
        $outputCost = $this->output * 0.000075;

        return $inputCost + $outputCost;
    }

    /**
     * Check if any tokens were used.
     */
    public function hasTokens(): bool
    {
        return $this->total() > 0;
    }

    /**
     * Add another token count to this one.
     */
    public function add(self $other): self
    {
        return new self(
            $this->input + $other->input,
            $this->output + $other->output
        );
    }

    /**
     * Format as human-readable string.
     */
    public function format(): string
    {
        return sprintf('%s in / %s out', number_format($this->input), number_format($this->output));
    }

    public function equals(self $other): bool
    {
        return $this->input === $other->input && $this->output === $other->output;
    }

    /**
     * Convert to array for serialization.
     *
     * @return array{input: int, output: int, total: int}
     */
    public function toArray(): array
    {
        return [
            'input' => $this->input,
            'output' => $this->output,
            'total' => $this->total(),
        ];
    }
}
← Übersicht Graph