Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
FontContext
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
2 / 2
3
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 textToHex
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3declare(strict_types=1);
4
5namespace Phpdftk\Pdf\Core\Interactive\Form;
6
7use Phpdftk\Pdf\Core\PdfReference;
8
9/**
10 * Carries font metadata needed to render custom (non-standard) fonts
11 * in form field appearance streams.
12 *
13 * When passed to AppearanceGenerator methods, the generator will:
14 * - Use hex-encoded glyph IDs instead of literal text strings
15 * - Wire the font reference into the FormXObject's /Resources
16 *
17 * Build via PdfWriter after calling addCompositeFont() / addOpenTypeFont():
18 *
19 *     $fontCtx = new FontContext(
20 *         fontRef:       new PdfReference($type0Font->objectNumber),
21 *         unicodeToGid:  $parsedData->fullUnicodeToGid,
22 *     );
23 */
24final class FontContext
25{
26    /**
27     * @param PdfReference         $fontRef      Indirect reference to the registered font object
28     * @param array<int, int>      $unicodeToGid Unicode codepoint → glyph ID mapping
29     */
30    public function __construct(
31        public readonly PdfReference $fontRef,
32        public readonly array $unicodeToGid,
33    ) {}
34
35    /**
36     * Convert a UTF-8 string to hex-encoded 2-byte glyph ID sequence.
37     */
38    public function textToHex(string $text): string
39    {
40        $hex = '';
41        foreach (mb_str_split($text) as $char) {
42            $cp = mb_ord($char);
43            $gid = $this->unicodeToGid[$cp] ?? 0;
44            $hex .= sprintf('%04X', $gid);
45        }
46        return $hex;
47    }
48}