|
1 | 1 | <?php |
2 | 2 |
|
| 3 | +use App\Enums\EscapedStringBacked; |
3 | 4 | use App\Enums\IntegerBacked; |
4 | 5 | use App\Enums\NonBacked; |
5 | 6 | use App\Enums\StringBacked; |
|
20 | 21 | ->toContain('class StringBacked extends Enum') |
21 | 22 | ->toContain(StringBacked::Active->name . ': Object.freeze({') |
22 | 23 | ->toContain("name: '" . StringBacked::Active->name . "',") |
23 | | - ->toContain("value: '" . StringBacked::Active->value . "',") |
| 24 | + ->toContain('value: ' . json_encode(StringBacked::Active->value) . ',') |
24 | 25 | ->toContain('export default StringBacked;'); |
25 | 26 | }); |
26 | 27 |
|
|
62 | 63 | ->toContain('export default NonBacked;'); |
63 | 64 | }); |
64 | 65 |
|
| 66 | +it('escapes string values and method return values that need it', function () { |
| 67 | + // Act. |
| 68 | + $this->artisan(GenerateEnumsCommand::class); |
| 69 | + |
| 70 | + $path = resource_path(config('paragon.enums.paths.generated') . DIRECTORY_SEPARATOR . 'EscapedStringBacked.ts'); |
| 71 | + $file = file_get_contents($path); |
| 72 | + |
| 73 | + // Assert. |
| 74 | + expect($path)->toBeFile() |
| 75 | + ->and($file) |
| 76 | + ->toContain('value: ' . json_encode(EscapedStringBacked::Quote->value) . ',') |
| 77 | + ->toContain('label: (): string => ' . json_encode(EscapedStringBacked::Quote->label()) . ','); |
| 78 | +}); |
| 79 | + |
| 80 | +it('throws instead of writing broken output for a value that cannot be encoded as JSON', function () { |
| 81 | + // Arrange. |
| 82 | + // Written directly into app_path() rather than tests/Fixtures: GenerateEnumsCommand |
| 83 | + // processes every enum under that path in a single pass, so a fixture there that |
| 84 | + // intentionally fails generation would break every test that runs the command. |
| 85 | + file_put_contents(app_path('Enums/InvalidUtf8Backed.php'), <<<'PHP' |
| 86 | + <?php |
| 87 | +
|
| 88 | + namespace App\Enums; |
| 89 | +
|
| 90 | + enum InvalidUtf8Backed: string |
| 91 | + { |
| 92 | + case Bad = "\xB1\x31"; |
| 93 | + } |
| 94 | + |
| 95 | + PHP); |
| 96 | + |
| 97 | + // Act. |
| 98 | + $this->artisan(GenerateEnumsCommand::class); |
| 99 | +})->throws(JsonException::class); |
| 100 | + |
65 | 101 | it('generates enums recursively', function () { |
66 | 102 | // Act. |
67 | 103 | $this->artisan(GenerateEnumsCommand::class); |
|
102 | 138 | // type definition |
103 | 139 | ->toContain('label();') |
104 | 140 | // items objects |
105 | | - ->toContain("label: (): string => '" . StringBacked::Active->label() . "',"); |
| 141 | + ->toContain('label: (): string => ' . json_encode(StringBacked::Active->label()) . ','); |
106 | 142 | }); |
107 | 143 |
|
108 | 144 | it('ignores methods with \'IgnoreParagon\' attribute', function () { |
|
0 commit comments