Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
76.92% covered (warning)
76.92%
10 / 13
50.00% covered (danger)
50.00%
3 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
JavascriptIdentifierKey
76.92% covered (warning)
76.92%
10 / 13
50.00% covered (danger)
50.00%
3 / 6
10.00
0.00% covered (danger)
0.00%
0 / 1
 toCode
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getRegularExpression
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 validate
50.00% covered (danger)
50.00%
1 / 2
0.00% covered (danger)
0.00%
0 / 1
2.50
 createFromText
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 createRandom
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 humanize
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2namespace Apie\TypescriptCodeBuilder\ValueObjects;
3
4use Apie\Core\Attributes\Description;
5use Apie\Core\Attributes\FakeMethod;
6use Apie\Core\Identifiers\KebabCaseSlug;
7use Apie\Core\Utils\IdentifierConstants;
8use Apie\Core\ValueObjects\Exceptions\InvalidStringForValueObjectException;
9use Apie\Core\ValueObjects\Interfaces\HasRegexValueObjectInterface;
10use Apie\Core\ValueObjects\IsStringWithRegexValueObject;
11use Faker\Generator;
12use ReflectionClass;
13
14#[FakeMethod('createRandom')]
15#[Description('A valid JavaScript identifier for keys of a javascript object')]
16class JavascriptIdentifierKey implements HasRegexValueObjectInterface
17{
18    use IsStringWithRegexValueObject;
19
20    public function toCode()
21    {
22        try {
23            $id = JavascriptIdentifier::fromNative($this->internal);
24            return $id->toNative();
25        } catch (InvalidStringForValueObjectException) {
26            return json_encode($this->internal);
27        }
28    }
29
30    public static function getRegularExpression(): string
31    {
32        return '/^[A-Za-z_][A-Za-z0-9_]*$/D';
33    }
34
35    public static function validate(string $input): void
36    {
37        if (!preg_match(static::getRegularExpression(), $input)) {
38            throw new InvalidStringForValueObjectException($input, new ReflectionClass(self::class));
39        }
40    }
41
42    public static function createFromText(string $input): static
43    {
44        if (!preg_match(static::getRegularExpression(), $input)) {
45            $input = KebabCaseSlug::fromText($input)->toCamelCaseSlug()->toNative();
46        }
47
48        return new self($input);
49    }
50
51    public static function createRandom(Generator $faker): static
52    {
53        $input = $faker->randomElement(IdentifierConstants::RANDOM_IDENTIFIERS);
54
55        return new static($input);
56    }
57
58    public function humanize(): string
59    {
60        return $this->toNative();
61    }
62}