Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
76.92% |
10 / 13 |
|
50.00% |
3 / 6 |
CRAP | |
0.00% |
0 / 1 |
| JavascriptIdentifierKey | |
76.92% |
10 / 13 |
|
50.00% |
3 / 6 |
10.00 | |
0.00% |
0 / 1 |
| toCode | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
| getRegularExpression | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| validate | |
50.00% |
1 / 2 |
|
0.00% |
0 / 1 |
2.50 | |||
| createFromText | |
66.67% |
2 / 3 |
|
0.00% |
0 / 1 |
2.15 | |||
| createRandom | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| humanize | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| 1 | <?php |
| 2 | namespace Apie\TypescriptCodeBuilder\ValueObjects; |
| 3 | |
| 4 | use Apie\Core\Attributes\Description; |
| 5 | use Apie\Core\Attributes\FakeMethod; |
| 6 | use Apie\Core\Identifiers\KebabCaseSlug; |
| 7 | use Apie\Core\Utils\IdentifierConstants; |
| 8 | use Apie\Core\ValueObjects\Exceptions\InvalidStringForValueObjectException; |
| 9 | use Apie\Core\ValueObjects\Interfaces\HasRegexValueObjectInterface; |
| 10 | use Apie\Core\ValueObjects\IsStringWithRegexValueObject; |
| 11 | use Faker\Generator; |
| 12 | use ReflectionClass; |
| 13 | |
| 14 | #[FakeMethod('createRandom')] |
| 15 | #[Description('A valid JavaScript identifier for keys of a javascript object')] |
| 16 | class 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 | } |