MessageContent.php

Code Hygiene Score: 100

Keine Issues gefunden.

Dependencies 1

Klassen 1

Funktionen 10

Verwendet von 3

Code

<?php

declare(strict_types=1);

namespace Domain\ValueObject;

// @responsibility: Immutables Value Object für Chat-Nachrichten-Inhalt

use InvalidArgumentException;

final class MessageContent
{
    private const MAX_LENGTH = 100000;

    private string $value;

    private function __construct(string $value)
    {
        $this->value = $value;
    }

    /**
     * Create from string.
     *
     * @throws InvalidArgumentException
     */
    public static function fromString(string $content): self
    {
        $content = trim($content);

        if ($content === '') {
            throw new InvalidArgumentException('Message content cannot be empty');
        }

        if (mb_strlen($content) > self::MAX_LENGTH) {
            throw new InvalidArgumentException(
                sprintf('Message content exceeds maximum length of %d characters', self::MAX_LENGTH)
            );
        }

        return new self($content);
    }

    /**
     * Create for system/assistant messages that may be empty initially.
     */
    public static function fromStringOrEmpty(string $content): self
    {
        return new self(trim($content));
    }

    public function value(): string
    {
        return $this->value;
    }

    public function __toString(): string
    {
        return $this->value;
    }

    public function isEmpty(): bool
    {
        return $this->value === '';
    }

    public function length(): int
    {
        return mb_strlen($this->value);
    }

    /**
     * Get preview of content (first N characters).
     */
    public function preview(int $maxLength = 50): string
    {
        if ($this->length() <= $maxLength) {
            return $this->value;
        }

        return mb_substr($this->value, 0, $maxLength) . '...';
    }

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

    /**
     * Check if content contains a search term (case-insensitive).
     */
    public function contains(string $needle): bool
    {
        return mb_stripos($this->value, $needle) !== false;
    }
}
← Übersicht Graph