Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
85.71% |
6 / 7 |
|
75.00% |
3 / 4 |
CRAP | |
0.00% |
0 / 1 |
| JavascriptIdentifier | |
85.71% |
6 / 7 |
|
75.00% |
3 / 4 |
6.10 | |
0.00% |
0 / 1 |
| getRegularExpression | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| validate | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
3 | |||
| createRandom | |
100.00% |
3 / 3 |
|
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\Utils\IdentifierConstants; |
| 7 | use Apie\Core\ValueObjects\Exceptions\InvalidStringForValueObjectException; |
| 8 | use Apie\Core\ValueObjects\Interfaces\HasRegexValueObjectInterface; |
| 9 | use Apie\Core\ValueObjects\IsStringWithRegexValueObject; |
| 10 | use Faker\Generator; |
| 11 | use ReflectionClass; |
| 12 | |
| 13 | #[FakeMethod('createRandom')] |
| 14 | #[Description('A valid JavaScript identifier that is not a reserved keyword')] |
| 15 | class JavascriptIdentifier implements HasRegexValueObjectInterface |
| 16 | { |
| 17 | use IsStringWithRegexValueObject; |
| 18 | |
| 19 | private const RESERVED_WORDS = [ |
| 20 | 'as', 'assert', 'async', 'await', 'break', 'case', 'catch', 'class', 'const', |
| 21 | 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'export', 'extends', |
| 22 | 'false', 'finally', 'for', 'from', 'function', 'get', 'if', 'implements', 'import', |
| 23 | 'in', 'instanceof', 'interface', 'let', 'new', 'null', 'of', 'package', 'private', |
| 24 | 'protected', 'public', 'return', 'set', 'static', 'super', 'switch', 'this', 'throw', |
| 25 | 'true', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield', |
| 26 | 'enum', 'eval', 'arguments', 'abstract', 'boolean', 'byte', 'char', 'double', 'final', |
| 27 | 'float', 'goto', 'int', 'long', 'native', 'short', 'synchronized', 'throws', |
| 28 | 'transient', 'volatile', |
| 29 | ]; |
| 30 | |
| 31 | public static function getRegularExpression(): string |
| 32 | { |
| 33 | return '/^[A-Za-z_][A-Za-z0-9_]*$/D'; |
| 34 | } |
| 35 | |
| 36 | public static function validate(string $input): void |
| 37 | { |
| 38 | if (!preg_match(static::getRegularExpression(), $input) || in_array($input, self::RESERVED_WORDS, true)) { |
| 39 | throw new InvalidStringForValueObjectException($input, new ReflectionClass(self::class)); |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | public static function createRandom(Generator $faker): static |
| 44 | { |
| 45 | do { |
| 46 | $input = $faker->randomElement(IdentifierConstants::RANDOM_IDENTIFIERS); |
| 47 | } while (in_array($input, self::RESERVED_WORDS, true)); |
| 48 | |
| 49 | return new static($input); |
| 50 | } |
| 51 | |
| 52 | public function humanize(): string |
| 53 | { |
| 54 | return $this->toNative(); |
| 55 | } |
| 56 | } |