Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
52.94% covered (warning)
52.94%
9 / 17
40.00% covered (danger)
40.00%
2 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
TranslationString
52.94% covered (warning)
52.94%
9 / 17
40.00% covered (danger)
40.00%
2 / 5
20.42
0.00% covered (danger)
0.00%
0 / 1
 getRegularExpression
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 toPath
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 toUnbounded
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 getLastTranslationSegment
77.78% covered (warning)
77.78%
7 / 9
0.00% covered (danger)
0.00%
0 / 1
4.18
 createForResourceName
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2namespace Apie\Core\Translator\ValueObjects;
3
4use Apie\Core\Attributes\Description;
5use Apie\Core\BoundedContext\BoundedContextId;
6use Apie\Core\Identifiers\SnakeCaseSlug;
7use Apie\Core\ValueObjects\Interfaces\HasRegexValueObjectInterface;
8use Apie\Core\ValueObjects\IsStringWithRegexValueObject;
9use ReflectionClass;
10
11#[Description('Represents a translation string/identifier')]
12final class TranslationString implements HasRegexValueObjectInterface
13{
14    use IsStringWithRegexValueObject;
15
16    public static function getRegularExpression(): string
17    {
18        return '/^[a-z0-9_]+(\.[a-z0-9_]+)*$/i';
19    }
20
21    public function toPath(string $rootPath): string
22    {
23        return rtrim($rootPath, '/') . '/' . str_replace('.', '/', $this->internal);
24    }
25
26    public function toUnbounded(): self
27    {
28        if (str_starts_with('apie.bounded.', $this->internal)) {
29            return new self(preg_replace('/^apie\.bounded\.[a-z0-9_]+\./i', 'apie.', $this->internal));
30        }
31        return $this;
32    }
33
34    public function getLastTranslationSegment(bool $trimUnderscoreAtStart = true): string
35    {
36        $fn = $trimUnderscoreAtStart ? function ($v) {
37            return ltrim($v, '_');
38        } : function ($v) {
39            return $v;
40        };
41        $pos = strrpos($this->internal, '.');
42        if ($pos === false || $pos === 0) {
43            return $fn($this->internal);
44        }
45        return $fn(substr(strrchr($this->internal, '.'), 1));
46    }
47
48    /**
49     * @param ReflectionClass<object> $class
50     */
51    public static function createForResourceName(ReflectionClass $class, ?BoundedContextId $boundedContextId = null): self
52    {
53        if ($boundedContextId === null) {
54            return new self('apie.resource.' . SnakeCaseSlug::fromClass($class) . '.singular');
55        }
56        return new self('apie.bounded.' .  $boundedContextId . '.resource.' . SnakeCaseSlug::fromClass($class) . '.singular');
57    }
58}