Lines 90.90% 10 / 11
Functions and Methods 80.00% 4 / 5
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
EntityId 90.90% 10 / 11 80.00% 4 / 5 8.05 0.00% 0 / 1
 __construct 100.00% 5 / 5 100.00% 1 / 1 2
 tryFromString 100.00% 3 / 3 100.00% 1 / 1 2
 fromStringOrId 100.00% 1 / 1 100.00% 1 / 1 2
 equals 100.00% 1 / 1 100.00% 1 / 1 1
 __toString 0.00% 0 / 1 0.00% 0 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Contracts\Entity;
6
7use Stewart\Contracts\Exception\IdentifierError;
8use Stewart\Contracts\Exception\IdentifierException;
9use Stringable;
10
11final readonly class EntityId implements Stringable
12{
13    private const string PATTERN = '/\A([a-z0-9_]+)\.([a-z0-9_]+)\z/';
14
15    public string $value;
16
17    public string $domain;
18
19    public string $objectId;
20
21    /** @throws IdentifierException */
22    public function __construct(string $value)
23    {
24        if (preg_match(self::PATTERN, $value, $parts) !== 1) {
25            throw IdentifierException::createForReason(IdentifierError::EntityIdInvalid, entityId: $value);
26        }
27
28        $this->value = $value;
29        $this->domain = $parts[1];
30        $this->objectId = $parts[2];
31    }
32
33    public static function tryFromString(string $value): ?self
34    {
35        try {
36            return new self($value);
37        } catch (IdentifierException) {
38            return null;
39        }
40    }
41
42    /** @throws IdentifierException */
43    public static function fromStringOrId(self|string $id): self
44    {
45        return $id instanceof self ? $id : new self($id);
46    }
47
48    public function equals(self $other): bool
49    {
50        return $this->value === $other->value;
51    }
52
53    public function __toString(): string
54    {
55        return $this->value;
56    }
57}