packages/sql-faker/tests/Unit/Generation/Value/Utf8Test.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\SqlFaker\Generation\Value;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\TestCase;
9use SqlFaker\Generation\Value\Utf8;
10
11#[CoversClass(Utf8::class)]
12final class Utf8Test extends TestCase
13{
14    #[\PHPUnit\Framework\Attributes\DataProvider('providerEncodings')]
15    public function testValidRecognizesScalarBoundariesAndWidthLimits(string $bytes, int $width, bool $valid): void
16    {
17        self::assertSame($valid, (new Utf8())->valid($bytes, $width));
18    }
19
20    /**
21     * @return iterable<array{string, int, bool}>
22     */
23    public static function providerEncodings(): iterable
24    {
25        foreach (['', "\0\x7f", 'é', '猫', '😀', "\xf4\x8f\xbf\xbf"] as $bytes) {
26            yield [$bytes, 4, true];
27        }
28        foreach (["\x80", "\xc0\x80", "\xe0\x80\x80", "\xed\xa0\x80", "\xf0\x80\x80\x80", "\xf4\x90\x80\x80", "\xf5\x80\x80\x80", "\xc2", "\xe2\x82", "\xe2a\x80"] as $bytes) {
29            yield [$bytes, 4, false];
30        }
31        yield ['ASCII', 1, true];
32        yield ['é', 1, false];
33        yield ['猫', 3, true];
34        yield ['😀', 3, false];
35        yield ["a\x80", 4, false];
36        yield ["\xc2\x7f", 4, false];
37        yield ["\xc2\x80", 4, true];
38        yield ["\xc2\xbf", 4, true];
39        yield ["\xc2\xc0", 4, false];
40        yield ["\xe0\x9f\xbf", 4, false];
41        yield ["\xe0\xa0\x80", 4, true];
42        yield ["\xed\x9f\xbf", 4, true];
43        yield ["\xf0\x8f\xbf\xbf", 4, false];
44        yield ["\xf0\x90\x80\x80", 4, true];
45    }
46
47    public function testValidReadsFourByteScalarsByDefault(): void
48    {
49        self::assertTrue((new Utf8())->valid('😀'));
50    }
51    public function testWidthClassifiesLeadingByteBoundaries(): void
52    {
53        $utf8 = new Utf8();
54        self::assertSame(1, $utf8->width(127));
55        self::assertSame(0, $utf8->width(128));
56        self::assertSame(0, $utf8->width(193));
57        self::assertSame(2, $utf8->width(194));
58        self::assertSame(3, $utf8->width(224));
59        self::assertSame(4, $utf8->width(240));
60        self::assertSame(4, $utf8->width(244));
61        self::assertSame(0, $utf8->width(245));
62    }
63}
64