SessionUuid.php

Code Hygiene Score: 100

Keine Issues gefunden.

Dependencies 1

Klassen 1

Funktionen 7

Verwendet von 3

Code

<?php

declare(strict_types=1);

namespace Domain\ValueObject;

// @responsibility: Immutables Value Object für Chat-Session-UUID

use InvalidArgumentException;

final class SessionUuid
{
    private const UUID_PATTERN = '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i';

    private string $value;

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

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

        if (!self::isValid($uuid)) {
            throw new InvalidArgumentException("Invalid UUID v4 format: {$uuid}");
        }

        return new self($uuid);
    }

    /**
     * Generate a new UUID v4.
     */
    public static function generate(): self
    {
        $data = random_bytes(16);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);

        $uuid = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));

        return new self($uuid);
    }

    /**
     * Check if a string is a valid UUID v4.
     */
    public static function isValid(string $uuid): bool
    {
        return preg_match(self::UUID_PATTERN, $uuid) === 1;
    }

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

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

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