Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
145 / 145
100.00% covered (success)
100.00%
12 / 12
CRAP
100.00% covered (success)
100.00%
1 / 1
TtfFileFaker
100.00% covered (success)
100.00%
145 / 145
100.00% covered (success)
100.00%
12 / 12
23
100.00% covered (success)
100.00%
1 / 1
 createOriginalFilename
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 createMimeType
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isSupported
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 createResource
100.00% covered (success)
100.00%
58 / 58
100.00% covered (success)
100.00%
1 / 1
3
 notdefContours
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 randomContour
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
3
 encodeGlyph
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
4
 createCmap
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 createName
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
2
 assemble
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
3
 pad
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 checksum
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2namespace Apie\Faker\FileFakers;
3
4use Apie\Faker\Interfaces\ApieFileFaker;
5use Faker\Generator;
6use Nyholm\Psr7\Stream;
7
8/**
9 * Generates a valid TrueType font with a random family name and random star shaped glyphs mapped to A, B, C, ...
10 */
11final class TtfFileFaker implements ApieFileFaker
12{
13    private const UNITS_PER_EM = 1000;
14    private const FIRST_CHAR = 0x41;
15    private const ASCENT = 800;
16    private const DESCENT = -200;
17
18    public function createOriginalFilename(Generator $faker): string
19    {
20        return $faker->word() . '.ttf';
21    }
22
23    public function createMimeType(): string
24    {
25        return 'font/ttf';
26    }
27
28    public static function isSupported(): bool
29    {
30        return true;
31    }
32
33    /** @return resource */
34    public function createResource(Generator $faker, string $originalFilename, string $mimeType): mixed
35    {
36        $glyphCount = $faker->numberBetween(5, 26);
37        $glyphs = [$this->notdefContours()];
38        for ($i = 0; $i < $glyphCount; $i++) {
39            $glyphs[] = [$this->randomContour($faker)];
40        }
41
42        $glyf = '';
43        $loca = '';
44        $metrics = '';
45        $bounds = [PHP_INT_MAX, PHP_INT_MAX, PHP_INT_MIN, PHP_INT_MIN];
46        $maxPoints = 0;
47        $maxContours = 0;
48        $advanceMax = 0;
49        foreach ($glyphs as $contours) {
50            $loca .= pack('N', strlen($glyf));
51            [$data, $box] = $this->encodeGlyph($contours);
52            $glyf .= $data;
53            $advance = $box[2] + 100;
54            $advanceMax = max($advanceMax, $advance);
55            $metrics .= pack('nn', $advance, $box[0]);
56            $bounds = [min($bounds[0], $box[0]), min($bounds[1], $box[1]), max($bounds[2], $box[2]), max($bounds[3], $box[3])];
57            $maxPoints = max($maxPoints, array_sum(array_map('count', $contours)));
58            $maxContours = max($maxContours, count($contours));
59        }
60        $loca .= pack('N', strlen($glyf));
61        $numGlyphs = count($glyphs);
62
63        $now = time() + 2082844800;
64        $head = pack('NNNN', 0x00010000, 0x00010000, 0, 0x5F0F3CF5)
65            . pack('nn', 0b11, self::UNITS_PER_EM)
66            . pack('JJ', $now, $now)
67            . pack('nnnn', ...$bounds)
68            . pack('nnnnnn', 0, 8, 2, 1, 0, 0);
69        $hhea = pack('N', 0x00010000)
70            . pack('nnn', self::ASCENT, self::DESCENT & 0xFFFF, 0)
71            . pack('nnnn', $advanceMax, $bounds[0], 0, $bounds[2])
72            . pack('nnn', 1, 0, 0)
73            . pack('nnnn', 0, 0, 0, 0)
74            . pack('nn', 0, $numGlyphs);
75        $maxp = pack('Nn', 0x00010000, $numGlyphs)
76            . pack('nnnnnnnnnnnnn', $maxPoints, $maxContours, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0);
77        $os2 = pack('nnnnn', 0, 500, 400, 5, 0)
78            . pack('nnnnnnnn', 650, 600, 0, 75, 650, 600, 0, 350)
79            . pack('nnn', 50, 300, 0)
80            . str_repeat("\0", 10)
81            . pack('NNNN', 1, 0, 0, 0)
82            . 'NONE'
83            . pack('nnnnnnnn', 0x40, self::FIRST_CHAR, self::FIRST_CHAR + $numGlyphs - 2, self::ASCENT, self::DESCENT & 0xFFFF, 0, self::ASCENT, -self::DESCENT);
84        $post = pack('NNnnNNNNN', 0x00030000, 0, -100, 50, 0, 0, 0, 0, 0);
85
86        $tables = [
87            'OS/2' => $os2,
88            'cmap' => $this->createCmap($numGlyphs - 1),
89            'glyf' => $glyf,
90            'head' => $head,
91            'hhea' => $hhea,
92            'hmtx' => $metrics,
93            'loca' => $loca,
94            'maxp' => $maxp,
95            'name' => $this->createName($faker),
96            'post' => $post,
97        ];
98
99        return Stream::create($this->assemble($tables))->detach();
100    }
101
102    /** @return array<int, array<int, array{int, int}>> */
103    private function notdefContours(): array
104    {
105        // outer contour clockwise, inner contour counter clockwise so it is a hole.
106        return [
107            [[50, 0], [50, 700], [450, 700], [450, 0]],
108            [[100, 50], [400, 50], [400, 650], [100, 650]],
109        ];
110    }
111
112    /** @return array<int, array{int, int}> */
113    private function randomContour(Generator $faker): array
114    {
115        $points = $faker->numberBetween(5, 12);
116        $centerX = 300;
117        $centerY = 350;
118        $contour = [];
119        // decreasing angles give a clockwise contour, which TrueType requires for outer contours.
120        for ($i = 0; $i < $points; $i++) {
121            $angle = 2 * M_PI * (1 - $i / $points);
122            $radius = $faker->numberBetween(120, 1000) / 1000 * ($i % 2 === 0 ? 1 : 0.55);
123            $contour[] = [
124                (int) round($centerX + cos($angle) * 250 * $radius),
125                (int) round($centerY + sin($angle) * 350 * $radius),
126            ];
127        }
128        return $contour;
129    }
130
131    /**
132     * @param array<int, array<int, array{int, int}>> $contours
133     * @return array{string, array{int, int, int, int}}
134     */
135    private function encodeGlyph(array $contours): array
136    {
137        $xs = [];
138        $ys = [];
139        $endPoints = '';
140        $total = 0;
141        foreach ($contours as $contour) {
142            foreach ($contour as [$x, $y]) {
143                $xs[] = $x;
144                $ys[] = $y;
145            }
146            $total += count($contour);
147            $endPoints .= pack('n', $total - 1);
148        }
149        $box = [min($xs), min($ys), max($xs), max($ys)];
150        $xData = '';
151        $yData = '';
152        $previousX = 0;
153        $previousY = 0;
154        foreach ($xs as $i => $x) {
155            $xData .= pack('n', $x - $previousX);
156            $yData .= pack('n', $ys[$i] - $previousY);
157            $previousX = $x;
158            $previousY = $ys[$i];
159        }
160        // flag 1: on curve point with 16 bit x and y deltas.
161        $data = pack('nnnnn', count($contours), ...$box) . $endPoints . pack('n', 0)
162            . str_repeat("\x01", $total) . $xData . $yData;
163
164        return [$this->pad($data), $box];
165    }
166
167    private function createCmap(int $characterCount): string
168    {
169        $last = self::FIRST_CHAR + $characterCount - 1;
170        // format 4 with a segment for the characters and the required terminating segment.
171        $subtable = pack('nnn', 4, 32, 0)
172            . pack('nnnn', 4, 4, 1, 0)
173            . pack('nn', $last, 0xFFFF) . pack('n', 0)
174            . pack('nn', self::FIRST_CHAR, 0xFFFF)
175            . pack('nn', 1 - self::FIRST_CHAR, 1)
176            . pack('nn', 0, 0);
177
178        return pack('nn', 0, 1) . pack('nnN', 3, 1, 12) . $subtable;
179    }
180
181    private function createName(Generator $faker): string
182    {
183        $family = ucfirst($faker->word()) . ucfirst($faker->word());
184        $strings = [
185            1 => $family,
186            2 => 'Regular',
187            3 => $family . ' ' . $faker->numerify('####') . ' Regular',
188            4 => $family . ' Regular',
189            5 => 'Version 1.0',
190            6 => $family . '-Regular',
191        ];
192        $records = '';
193        $storage = '';
194        foreach ($strings as $id => $string) {
195            $encoded = mb_convert_encoding($string, 'UTF-16BE', 'UTF-8');
196            $records .= pack('nnnnnn', 3, 1, 0x409, $id, strlen($encoded), strlen($storage));
197            $storage .= $encoded;
198        }
199
200        return pack('nnn', 0, count($strings), 6 + 12 * count($strings)) . $records . $storage;
201    }
202
203    /** @param array<string, string> $tables */
204    private function assemble(array $tables): string
205    {
206        $count = count($tables);
207        $entrySelector = (int) floor(log($count, 2));
208        $searchRange = 16 * (2 ** $entrySelector);
209        $header = pack('Nnnnn', 0x00010000, $count, $searchRange, $entrySelector, $count * 16 - $searchRange);
210
211        $offset = 12 + 16 * $count;
212        $directory = '';
213        $body = '';
214        $headOffset = 0;
215        foreach ($tables as $tag => $data) {
216            if ($tag === 'head') {
217                $headOffset = strlen($body);
218            }
219            $directory .= $tag . pack('NNN', $this->checksum($data), $offset + strlen($body), strlen($data));
220            $body .= $this->pad($data);
221        }
222        $font = $header . $directory . $body;
223        $adjustment = (0xB1B0AFBA - $this->checksum($font)) & 0xFFFFFFFF;
224
225        return substr_replace($font, pack('N', $adjustment), $offset + $headOffset + 8, 4);
226    }
227
228    private function pad(string $data): string
229    {
230        return $data . str_repeat("\0", (4 - strlen($data) % 4) % 4);
231    }
232
233    private function checksum(string $data): int
234    {
235        $sum = 0;
236        foreach (unpack('N*', $this->pad($data)) as $value) {
237            $sum = ($sum + $value) & 0xFFFFFFFF;
238        }
239        return $sum;
240    }
241}