Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
PdfString
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
2 / 2
13
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
 toPdf
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
12
1<?php
2
3declare(strict_types=1);
4
5namespace Phpdftk\Pdf\Core;
6
7/**
8 * Represents a PDF literal string (text) or a hex string <hex>.
9 */
10class PdfString implements Serializable
11{
12    public function __construct(
13        public readonly string $value,
14        public readonly bool $hex = false,
15    ) {}
16
17    public function toPdf(): string
18    {
19        if ($this->hex) {
20            return '<' . bin2hex($this->value) . '>';
21        }
22
23        // Literal string: escape backslash, parentheses, and control chars
24        $escaped = '';
25        $len = strlen($this->value);
26        for ($i = 0; $i < $len; $i++) {
27            $c = $this->value[$i];
28            $escaped .= match ($c) {
29                '\\' => '\\\\',
30                '('  => '\\(',
31                ')'  => '\\)',
32                "\n" => '\\n',
33                "\r" => '\\r',
34                "\t" => '\\t',
35                "\x08" => '\\b',
36                "\x0C" => '\\f',
37                default => $c,
38            };
39        }
40
41        return '(' . $escaped . ')';
42    }
43}