Passed
Pull Request — master (#517)
by
unknown
02:22
created

Font::calculateTextWidth()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 16
nc 3
nop 2
dl 0
loc 24
ccs 17
cts 17
cp 1
crap 5
rs 9.4222
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @file
5
 *          This file is part of the PdfParser library.
6
 *
7
 * @author  Sébastien MALOT <[email protected]>
8
 * @date    2017-01-03
9
 *
10
 * @license LGPLv3
11
 * @url     <https://github.com/smalot/pdfparser>
12
 *
13
 *  PdfParser is a pdf library written in PHP, extraction oriented.
14
 *  Copyright (C) 2017 - Sébastien MALOT <[email protected]>
15
 *
16
 *  This program is free software: you can redistribute it and/or modify
17
 *  it under the terms of the GNU Lesser General Public License as published by
18
 *  the Free Software Foundation, either version 3 of the License, or
19
 *  (at your option) any later version.
20
 *
21
 *  This program is distributed in the hope that it will be useful,
22
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
 *  GNU Lesser General Public License for more details.
25
 *
26
 *  You should have received a copy of the GNU Lesser General Public License
27
 *  along with this program.
28
 *  If not, see <http://www.pdfparser.org/sites/default/LICENSE.txt>.
29
 */
30
31
namespace Smalot\PdfParser;
32
33
use Smalot\PdfParser\Encoding\WinAnsiEncoding;
34
use Smalot\PdfParser\Exception\EncodingNotFoundException;
35
36
/**
37
 * Class Font
38
 */
39
class Font extends PDFObject
40
{
41
    const MISSING = '?';
42
43
    /**
44
     * @var array
45
     */
46
    protected $table = null;
47
48
    /**
49
     * @var array
50
     */
51
    protected $tableSizes = null;
52
53
    /**
54
     * Caches results from uchr.
55
     *
56
     * @var array
57
     */
58
    private static $uchrCache = [];
59
60
    /**
61
     * In some PDF-files encoding could be referenced by object id but object itself does not contain
62
     * `/Type /Encoding` in its dictionary. These objects wouldn't be initialized as Encoding in
63
     * \Smalot\PdfParser\PDFObject::factory() during file parsing (they would be just PDFObject).
64
     *
65
     * Therefore, we create an instance of Encoding from them during decoding and cache this value in this property.
66
     *
67
     * @var Encoding
68
     *
69
     * @see https://github.com/smalot/pdfparser/pull/500
70
     */
71
    private $initializedEncodingByPdfObject;
72
73 39
    public function init()
74
    {
75
        // Load translate table.
76 39
        $this->loadTranslateTable();
77 39
    }
78
79 3
    public function getName(): string
80
    {
81 3
        return $this->has('BaseFont') ? (string) $this->get('BaseFont') : '[Unknown]';
82
    }
83
84 3
    public function getType(): string
85
    {
86 3
        return (string) $this->header->get('Subtype');
87
    }
88
89 2
    public function getDetails(bool $deep = true): array
90
    {
91 2
        $details = [];
92
93 2
        $details['Name'] = $this->getName();
94 2
        $details['Type'] = $this->getType();
95 2
        $details['Encoding'] = ($this->has('Encoding') ? (string) $this->get('Encoding') : 'Ansi');
96
97 2
        $details += parent::getDetails($deep);
98
99 2
        return $details;
100
    }
101
102
    /**
103
     * @return string|bool
104
     */
105 22
    public function translateChar(string $char, bool $use_default = true)
106
    {
107 22
        $dec = hexdec(bin2hex($char));
108
109 22
        if (\array_key_exists($dec, $this->table)) {
110 19
            return $this->table[$dec];
111
        }
112
113
        // fallback for decoding single-byte ANSI characters that are not in the lookup table
114 6
        $fallbackDecoded = $char;
115
        if (
116 6
            \strlen($char) < 2
117 6
            && $this->has('Encoding')
118 6
            && $this->get('Encoding') instanceof Encoding
0 ignored issues
show
introduced by
$this->get('Encoding') is never a sub-type of Smalot\PdfParser\Encoding.
Loading history...
119
        ) {
120
            try {
121 2
                if (WinAnsiEncoding::class === $this->get('Encoding')->__toString()) {
122 1
                    $fallbackDecoded = self::uchr($dec);
123
                }
124 1
            } catch (EncodingNotFoundException $e) {
125
                // Encoding->getEncodingClass() throws EncodingNotFoundException when BaseEncoding doesn't exists
126
                // See table 5.11 on PDF 1.5 specs for more info
127
            }
128
        }
129
130 6
        return $use_default ? self::MISSING : $fallbackDecoded;
131
    }
132
133
    /**
134
     * Convert unicode character code to "utf-8" encoded string.
135
     */
136 37
    public static function uchr(int $code): string
137
    {
138 37
        if (!isset(self::$uchrCache[$code])) {
139
            // html_entity_decode() will not work with UTF-16 or UTF-32 char entities,
140
            // therefore, we use mb_convert_encoding() instead
141 13
            self::$uchrCache[$code] = mb_convert_encoding("&#{$code};", 'UTF-8', 'HTML-ENTITIES');
142
        }
143
144 37
        return self::$uchrCache[$code];
145
    }
146
147
    /**
148
     * Init internal chars translation table by ToUnicode CMap.
149
     */
150 39
    public function loadTranslateTable(): array
151
    {
152 39
        if (null !== $this->table) {
153 1
            return $this->table;
154
        }
155
156 39
        $this->table = [];
157 39
        $this->tableSizes = [
158
            'from' => 1,
159
            'to' => 1,
160
        ];
161
162 39
        if ($this->has('ToUnicode')) {
163 32
            $content = $this->get('ToUnicode')->getContent();
164 32
            $matches = [];
165
166
            // Support for multiple spacerange sections
167 32
            if (preg_match_all('/begincodespacerange(?P<sections>.*?)endcodespacerange/s', $content, $matches)) {
168 32
                foreach ($matches['sections'] as $section) {
169 32
                    $regexp = '/<(?P<from>[0-9A-F]+)> *<(?P<to>[0-9A-F]+)>[ \r\n]+/is';
170
171 32
                    preg_match_all($regexp, $section, $matches);
172
173 32
                    $this->tableSizes = [
174 32
                        'from' => max(1, \strlen(current($matches['from'])) / 2),
175 32
                        'to' => max(1, \strlen(current($matches['to'])) / 2),
176
                    ];
177
178 32
                    break;
179
                }
180
            }
181
182
            // Support for multiple bfchar sections
183 32
            if (preg_match_all('/beginbfchar(?P<sections>.*?)endbfchar/s', $content, $matches)) {
184 13
                foreach ($matches['sections'] as $section) {
185 13
                    $regexp = '/<(?P<from>[0-9A-F]+)> +<(?P<to>[0-9A-F]+)>[ \r\n]+/is';
186
187 13
                    preg_match_all($regexp, $section, $matches);
188
189 13
                    $this->tableSizes['from'] = max(1, \strlen(current($matches['from'])) / 2);
190
191 13
                    foreach ($matches['from'] as $key => $from) {
192 13
                        $parts = preg_split(
193 13
                            '/([0-9A-F]{4})/i',
194 13
                            $matches['to'][$key],
195 13
                            0,
196 13
                            \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE
197
                        );
198 13
                        $text = '';
199 13
                        foreach ($parts as $part) {
200 13
                            $text .= self::uchr(hexdec($part));
0 ignored issues
show
Bug introduced by
It seems like hexdec($part) can also be of type double; however, parameter $code of Smalot\PdfParser\Font::uchr() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

200
                            $text .= self::uchr(/** @scrutinizer ignore-type */ hexdec($part));
Loading history...
201
                        }
202 13
                        $this->table[hexdec($from)] = $text;
203
                    }
204
                }
205
            }
206
207
            // Support for multiple bfrange sections
208 32
            if (preg_match_all('/beginbfrange(?P<sections>.*?)endbfrange/s', $content, $matches)) {
209 25
                foreach ($matches['sections'] as $section) {
210
                    // Support for : <srcCode1> <srcCode2> <dstString>
211 25
                    $regexp = '/<(?P<from>[0-9A-F]+)> *<(?P<to>[0-9A-F]+)> *<(?P<offset>[0-9A-F]+)>[ \r\n]+/is';
212
213 25
                    preg_match_all($regexp, $section, $matches);
214
215 25
                    foreach ($matches['from'] as $key => $from) {
216 25
                        $char_from = hexdec($from);
217 25
                        $char_to = hexdec($matches['to'][$key]);
218 25
                        $offset = hexdec($matches['offset'][$key]);
219
220 25
                        for ($char = $char_from; $char <= $char_to; ++$char) {
221 25
                            $this->table[$char] = self::uchr($char - $char_from + $offset);
222
                        }
223
                    }
224
225
                    // Support for : <srcCode1> <srcCodeN> [<dstString1> <dstString2> ... <dstStringN>]
226
                    // Some PDF file has 2-byte Unicode values on new lines > added \r\n
227 25
                    $regexp = '/<(?P<from>[0-9A-F]+)> *<(?P<to>[0-9A-F]+)> *\[(?P<strings>[\r\n<>0-9A-F ]+)\][ \r\n]+/is';
228
229 25
                    preg_match_all($regexp, $section, $matches);
230
231 25
                    foreach ($matches['from'] as $key => $from) {
232 1
                        $char_from = hexdec($from);
233 1
                        $strings = [];
234
235 1
                        preg_match_all('/<(?P<string>[0-9A-F]+)> */is', $matches['strings'][$key], $strings);
236
237 1
                        foreach ($strings['string'] as $position => $string) {
238 1
                            $parts = preg_split(
239 1
                                '/([0-9A-F]{4})/i',
240
                                $string,
241 1
                                0,
242 1
                                \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE
243
                            );
244 1
                            $text = '';
245 1
                            foreach ($parts as $part) {
246 1
                                $text .= self::uchr(hexdec($part));
247
                            }
248 1
                            $this->table[$char_from + $position] = $text;
249
                        }
250
                    }
251
                }
252
            }
253
        }
254
255 39
        return $this->table;
256
    }
257
258
    /**
259
     * Set custom char translation table where:
260
     * - key - integer character code;
261
     * - value - "utf-8" encoded value;
262
     *
263
     * @return void
264
     */
265 1
    public function setTable(array $table)
266
    {
267 1
        $this->table = $table;
268 1
    }
269
270
    /**
271
     * Calculate text width with data from header 'Widths'. If width of character is not found then character is added to missing array.
272
     */
273 1
    public function calculateTextWidth($text, &$missing = null): float
274
    {
275 1
        $index_map = array_flip($this->table);
276 1
        $details = $this->getDetails();
277 1
        $widths = $details['Widths'];
278
279
        // Widths array is zero indexed but table is not. We must map them based on FirstChar and LastChar
280 1
        $width_map = array_flip(range($details['FirstChar'], $details['LastChar']));
281
282 1
        $width = 0;
283 1
        $missing = [];
284 1
        $textLength = mb_strlen($text);
285 1
        for ($i = 0; $i < $textLength; ++$i) {
286 1
            $char = mb_substr($text, $i, 1);
287 1
            if (!\array_key_exists($char, $index_map) || !\array_key_exists($index_map[$char], $width_map) ||
288 1
                !\array_key_exists($width_map[$index_map[$char]], $widths)) {
289 1
                $missing[] = $char;
290 1
                continue;
291
            }
292 1
            $width_index = $width_map[$index_map[$char]];
293 1
            $width += $widths[$width_index];
294
        }
295
296 1
        return $width;
297
    }
298
299
    /**
300
     * Decode hexadecimal encoded string. If $add_braces is true result value would be wrapped by parentheses.
301
     */
302 42
    public static function decodeHexadecimal(string $hexa, bool $add_braces = false): string
303
    {
304
        // Special shortcut for XML content.
305 42
        if (false !== stripos($hexa, '<?xml')) {
306 2
            return $hexa;
307
        }
308
309 42
        $text = '';
310 42
        $parts = preg_split('/(<[a-f0-9]+>)/si', $hexa, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE);
311
312 42
        foreach ($parts as $part) {
313 42
            if (preg_match('/^<.*>$/s', $part) && false === stripos($part, '<?xml')) {
314
                // strip line breaks
315 13
                $part = preg_replace("/[\r\n]/", '', $part);
316 13
                $part = trim($part, '<>');
317 13
                if ($add_braces) {
318 1
                    $text .= '(';
319
                }
320
321 13
                $part = pack('H*', $part);
322 13
                $text .= ($add_braces ? preg_replace('/\\\/s', '\\\\\\', $part) : $part);
323
324 13
                if ($add_braces) {
325 13
                    $text .= ')';
326
                }
327
            } else {
328 42
                $text .= $part;
329
            }
330
        }
331
332 42
        return $text;
333
    }
334
335
    /**
336
     * Decode string with octal-decoded chunks.
337
     */
338 42
    public static function decodeOctal(string $text): string
339
    {
340 42
        $parts = preg_split('/(\\\\[0-7]{3})/s', $text, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE);
341 42
        $text = '';
342
343 42
        foreach ($parts as $part) {
344 42
            if (preg_match('/^\\\\[0-7]{3}$/', $part)) {
345 19
                $text .= \chr(octdec(trim($part, '\\')));
0 ignored issues
show
Bug introduced by
It seems like octdec(trim($part, '\')) can also be of type double; however, parameter $codepoint of chr() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

345
                $text .= \chr(/** @scrutinizer ignore-type */ octdec(trim($part, '\\')));
Loading history...
346
            } else {
347 42
                $text .= $part;
348
            }
349
        }
350
351 42
        return $text;
352
    }
353
354
    /**
355
     * Decode string with html entity encoded chars.
356
     */
357 56
    public static function decodeEntities(string $text): string
358
    {
359 56
        $parts = preg_split('/(#\d{2})/s', $text, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE);
360 56
        $text = '';
361
362 56
        foreach ($parts as $part) {
363 56
            if (preg_match('/^#\d{2}$/', $part)) {
364 4
                $text .= \chr(hexdec(trim($part, '#')));
0 ignored issues
show
Bug introduced by
It seems like hexdec(trim($part, '#')) can also be of type double; however, parameter $codepoint of chr() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

364
                $text .= \chr(/** @scrutinizer ignore-type */ hexdec(trim($part, '#')));
Loading history...
365
            } else {
366 56
                $text .= $part;
367
            }
368
        }
369
370 56
        return $text;
371
    }
372
373
    /**
374
     * Check if given string is Unicode text (by BOM);
375
     * If true - decode to "utf-8" encoded string.
376
     * Otherwise - return text as is.
377
     *
378
     * @todo Rename in next major release to make the name correspond to reality (for ex. decodeIfUnicode())
379
     */
380 42
    public static function decodeUnicode(string $text): string
381
    {
382 42
        if (preg_match('/^\xFE\xFF/i', $text)) {
383
            // Strip U+FEFF byte order marker.
384 26
            $decode = substr($text, 2);
385 26
            $text = '';
386 26
            $length = \strlen($decode);
387
388 26
            for ($i = 0; $i < $length; $i += 2) {
389 26
                $text .= self::uchr(hexdec(bin2hex(substr($decode, $i, 2))));
0 ignored issues
show
Bug introduced by
It seems like hexdec(bin2hex(substr($decode, $i, 2))) can also be of type double; however, parameter $code of Smalot\PdfParser\Font::uchr() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

389
                $text .= self::uchr(/** @scrutinizer ignore-type */ hexdec(bin2hex(substr($decode, $i, 2))));
Loading history...
390
            }
391
        }
392
393 42
        return $text;
394
    }
395
396
    /**
397
     * @todo Deprecated, use $this->config->getFontSpaceLimit() instead.
398
     */
399 21
    protected function getFontSpaceLimit(): int
400
    {
401 21
        return $this->config->getFontSpaceLimit();
402
    }
403
404
    /**
405
     * Decode text by commands array.
406
     */
407 21
    public function decodeText(array $commands): string
408
    {
409 21
        $word_position = 0;
410 21
        $words = [];
411 21
        $font_space = $this->getFontSpaceLimit();
412
413 21
        foreach ($commands as $command) {
414 21
            switch ($command[PDFObject::TYPE]) {
415 21
                case 'n':
416 16
                    if ((float) (trim($command[PDFObject::COMMAND])) < $font_space) {
417 8
                        $word_position = \count($words);
418
                    }
419 16
                    continue 2;
420 21
                case '<':
421
                    // Decode hexadecimal.
422 11
                    $text = self::decodeHexadecimal('<'.$command[PDFObject::COMMAND].'>');
423 11
                    break;
424
425
                default:
426
                    // Decode octal (if necessary).
427 14
                    $text = self::decodeOctal($command[PDFObject::COMMAND]);
428
            }
429
430
            // replace escaped chars
431 21
            $text = str_replace(
432 21
                ['\\\\', '\(', '\)', '\n', '\r', '\t', '\f', '\ '],
433 21
                ['\\', '(', ')', "\n", "\r", "\t", "\f", ' '],
434
                $text
435
            );
436
437
            // add content to result string
438 21
            if (isset($words[$word_position])) {
439 16
                $words[$word_position] .= $text;
440
            } else {
441 21
                $words[$word_position] = $text;
442
            }
443
        }
444
445 21
        foreach ($words as &$word) {
446 21
            $word = $this->decodeContent($word);
447
        }
448
449 21
        return implode(' ', $words);
450
    }
451
452
    /**
453
     * Decode given $text to "utf-8" encoded string.
454
     *
455
     * @param bool $unicode This parameter is deprecated and might be removed in a future release
456
     */
457 23
    public function decodeContent(string $text, ?bool &$unicode = null): string
0 ignored issues
show
Unused Code introduced by
The parameter $unicode is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

457
    public function decodeContent(string $text, /** @scrutinizer ignore-unused */ ?bool &$unicode = null): string

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
458
    {
459 23
        if ($this->has('ToUnicode')) {
460 19
            return $this->decodeContentByToUnicodeCMapOrDescendantFonts($text);
461
        }
462
463 15
        if ($this->has('Encoding')) {
464 11
            $result = $this->decodeContentByEncoding($text);
465
466 11
            if (null !== $result) {
467 11
                return $result;
468
            }
469
        }
470
471 8
        return $this->decodeContentByAutodetectIfNecessary($text);
472
    }
473
474
    /**
475
     * First try to decode $text by ToUnicode CMap.
476
     * If char translation not found in ToUnicode CMap tries:
477
     *  - If DescendantFonts exists tries to decode char by one of that fonts.
478
     *      - If have no success to decode by DescendantFonts interpret $text as a string with "Windows-1252" encoding.
479
     *  - If DescendantFonts does not exist just return "?" as decoded char.
480
     *
481
     * @todo Seems this is invalid algorithm that do not follow pdf-format specification. Must be rewritten.
482
     */
483 19
    private function decodeContentByToUnicodeCMapOrDescendantFonts(string $text): string
484
    {
485 19
        $bytes = $this->tableSizes['from'];
486
487 19
        if ($bytes) {
488 19
            $result = '';
489 19
            $length = \strlen($text);
490
491 19
            for ($i = 0; $i < $length; $i += $bytes) {
492 19
                $char = substr($text, $i, $bytes);
493
494 19
                if (false !== ($decoded = $this->translateChar($char, false))) {
495 19
                    $char = $decoded;
496
                } elseif ($this->has('DescendantFonts')) {
497
                    if ($this->get('DescendantFonts') instanceof PDFObject) {
498
                        $fonts = $this->get('DescendantFonts')->getHeader()->getElements();
0 ignored issues
show
Bug introduced by
The method getHeader() does not exist on Smalot\PdfParser\Element. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

498
                        $fonts = $this->get('DescendantFonts')->/** @scrutinizer ignore-call */ getHeader()->getElements();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
499
                    } else {
500
                        $fonts = $this->get('DescendantFonts')->getContent();
501
                    }
502
                    $decoded = false;
503
504
                    foreach ($fonts as $font) {
505
                        if ($font instanceof self) {
506
                            if (false !== ($decoded = $font->translateChar($char, false))) {
507
                                $decoded = mb_convert_encoding($decoded, 'UTF-8', 'Windows-1252');
0 ignored issues
show
Bug introduced by
It seems like $decoded can also be of type true; however, parameter $string of mb_convert_encoding() does only seem to accept array|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

507
                                $decoded = mb_convert_encoding(/** @scrutinizer ignore-type */ $decoded, 'UTF-8', 'Windows-1252');
Loading history...
508
                                break;
509
                            }
510
                        }
511
                    }
512
513
                    if (false !== $decoded) {
514
                        $char = $decoded;
515
                    } else {
516
                        $char = mb_convert_encoding($char, 'UTF-8', 'Windows-1252');
517
                    }
518
                } else {
519
                    $char = self::MISSING;
520
                }
521
522 19
                $result .= $char;
523
            }
524
525 19
            $text = $result;
526
        }
527
528 19
        return $text;
529
    }
530
531
    /**
532
     * Decode content by any type of Encoding (dictionary's item) instance.
533
     */
534 11
    private function decodeContentByEncoding(string $text): ?string
535
    {
536 11
        $encoding = $this->get('Encoding');
537
538
        // When Encoding referenced by object id (/Encoding 520 0 R) but object itself does not contain `/Type /Encoding` in it's dictionary.
539 11
        if ($encoding instanceof PDFObject) {
0 ignored issues
show
introduced by
$encoding is never a sub-type of Smalot\PdfParser\PDFObject.
Loading history...
540 3
            $encoding = $this->getInitializedEncodingByPdfObject($encoding);
541
        }
542
543
        // When Encoding referenced by object id (/Encoding 520 0 R) but object itself contains `/Type /Encoding` in it's dictionary.
544 11
        if ($encoding instanceof Encoding) {
0 ignored issues
show
introduced by
$encoding is never a sub-type of Smalot\PdfParser\Encoding.
Loading history...
545 3
            return $this->decodeContentByEncodingEncoding($text, $encoding);
546
        }
547
548
        // When Encoding is just string (/Encoding /WinAnsiEncoding)
549 8
        if ($encoding instanceof Element) { //todo: ElementString class must by used?
0 ignored issues
show
introduced by
$encoding is always a sub-type of Smalot\PdfParser\Element.
Loading history...
550 8
            return $this->decodeContentByEncodingElement($text, $encoding);
551
        }
552
553
        // don't double-encode strings already in UTF-8
554
        if (!mb_check_encoding($text, 'UTF-8')) {
555
            return mb_convert_encoding($text, 'UTF-8', 'Windows-1252');
556
        }
557
558
        return $text;
559
    }
560
561
    /**
562
     * Returns already created or create a new one if not created before Encoding instance by PDFObject instance.
563
     */
564 3
    private function getInitializedEncodingByPdfObject(PDFObject $PDFObject): Encoding
565
    {
566 3
        if (!$this->initializedEncodingByPdfObject) {
567 3
            $this->initializedEncodingByPdfObject = $this->createInitializedEncodingByPdfObject($PDFObject);
568
        }
569
570 3
        return $this->initializedEncodingByPdfObject;
571
    }
572
573
    /**
574
     * Decode content when $encoding (given by $this->get('Encoding')) is instance of Encoding.
575
     */
576 3
    private function decodeContentByEncodingEncoding(string $text, Encoding $encoding): string
577
    {
578 3
        $result = '';
579 3
        $length = \strlen($text);
580
581 3
        for ($i = 0; $i < $length; ++$i) {
582 3
            $dec_av = hexdec(bin2hex($text[$i]));
583 3
            $dec_ap = $encoding->translateChar($dec_av);
584 3
            $result .= self::uchr($dec_ap ?? $dec_av);
0 ignored issues
show
Bug introduced by
It seems like $dec_ap ?? $dec_av can also be of type double; however, parameter $code of Smalot\PdfParser\Font::uchr() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

584
            $result .= self::uchr(/** @scrutinizer ignore-type */ $dec_ap ?? $dec_av);
Loading history...
585
        }
586
587 3
        return $result;
588
    }
589
590
    /**
591
     * Decode content when $encoding (given by $this->get('Encoding')) is instance of Element.
592
     */
593 8
    private function decodeContentByEncodingElement(string $text, Element $encoding): ?string
594
    {
595 8
        $pdfEncodingName = $encoding->getContent();
596
597
        // mb_convert_encoding does not support MacRoman/macintosh,
598
        // so we use iconv() here
599 8
        $iconvEncodingName = $this->getIconvEncodingNameOrNullByPdfEncodingName($pdfEncodingName);
600
601 8
        return $iconvEncodingName ? iconv($iconvEncodingName, 'UTF-8', $text) : null;
602
    }
603
604
    /**
605
     * Convert PDF encoding name to iconv-known encoding name.
606
     */
607 8
    private function getIconvEncodingNameOrNullByPdfEncodingName(string $pdfEncodingName): ?string
608
    {
609
        $pdfToIconvEncodingNameMap = [
610 8
            'StandardEncoding' => 'ISO-8859-1',
611
            'MacRomanEncoding' => 'MACINTOSH',
612
            'WinAnsiEncoding' => 'CP1252',
613
        ];
614
615 8
        return \array_key_exists($pdfEncodingName, $pdfToIconvEncodingNameMap)
616 8
            ? $pdfToIconvEncodingNameMap[$pdfEncodingName]
617 8
            : null;
618
    }
619
620
    /**
621
     * If string seems like "utf-8" encoded string do nothing and just return given string as is.
622
     * Otherwise, interpret string as "Window-1252" encoded string.
623
     *
624
     * @return string|false
625
     */
626 8
    private function decodeContentByAutodetectIfNecessary(string $text)
627
    {
628 8
        if (mb_check_encoding($text, 'UTF-8')) {
629 8
            return $text;
630
        }
631
632 1
        return mb_convert_encoding($text, 'UTF-8', 'Windows-1252');
0 ignored issues
show
Bug Best Practice introduced by
The expression return mb_convert_encodi...UTF-8', 'Windows-1252') also could return the type array which is incompatible with the documented return type false|string.
Loading history...
633
        //todo: Why exactly `Windows-1252` used?
634
    }
635
636
    /**
637
     * Create Encoding instance by PDFObject instance and init it.
638
     */
639 3
    private function createInitializedEncodingByPdfObject(PDFObject $PDFObject): Encoding
640
    {
641 3
        $encoding = $this->createEncodingByPdfObject($PDFObject);
642 3
        $encoding->init();
643
644 3
        return $encoding;
645
    }
646
647
    /**
648
     * Create Encoding instance by PDFObject instance (without init).
649
     */
650 3
    private function createEncodingByPdfObject(PDFObject $PDFObject): Encoding
651
    {
652 3
        $document = $PDFObject->getDocument();
653 3
        $header = $PDFObject->getHeader();
654 3
        $content = $PDFObject->getContent();
655 3
        $config = $PDFObject->getConfig();
656
657 3
        return new Encoding($document, $header, $content, $config);
658
    }
659
}
660