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

Font::decodeOctal()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
dl 0
loc 14
rs 10
c 1
b 0
f 0
ccs 8
cts 8
cp 1
cc 3
nc 3
nop 1
crap 3
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
        for ($i = 0; $i < mb_strlen($text); ++$i) {
285 1
            $char = mb_substr($text, $i, 1);
286 1
            if (!\array_key_exists($char, $index_map)) {
287 1
                $missing[] = $char;
288 1
                continue;
289
            }
290 1
            $width_index = $width_map[$index_map[$char]];
291 1
            $width += $widths[$width_index];
292
        }
293
294 1
        return $width;
295
    }
296
297
    /**
298
     * Decode hexadecimal encoded string. If $add_braces is true result value would be wrapped by parentheses.
299
     */
300 42
    public static function decodeHexadecimal(string $hexa, bool $add_braces = false): string
301
    {
302
        // Special shortcut for XML content.
303 42
        if (false !== stripos($hexa, '<?xml')) {
304 2
            return $hexa;
305
        }
306
307 42
        $text = '';
308 42
        $parts = preg_split('/(<[a-f0-9]+>)/si', $hexa, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE);
309
310 42
        foreach ($parts as $part) {
311 42
            if (preg_match('/^<.*>$/s', $part) && false === stripos($part, '<?xml')) {
312
                // strip line breaks
313 13
                $part = preg_replace("/[\r\n]/", '', $part);
314 13
                $part = trim($part, '<>');
315 13
                if ($add_braces) {
316 1
                    $text .= '(';
317
                }
318
319 13
                $part = pack('H*', $part);
320 13
                $text .= ($add_braces ? preg_replace('/\\\/s', '\\\\\\', $part) : $part);
321
322 13
                if ($add_braces) {
323 13
                    $text .= ')';
324
                }
325
            } else {
326 42
                $text .= $part;
327
            }
328
        }
329
330 42
        return $text;
331
    }
332
333
    /**
334
     * Decode string with octal-decoded chunks.
335
     */
336 42
    public static function decodeOctal(string $text): string
337
    {
338 42
        $parts = preg_split('/(\\\\[0-7]{3})/s', $text, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE);
339 42
        $text = '';
340
341 42
        foreach ($parts as $part) {
342 42
            if (preg_match('/^\\\\[0-7]{3}$/', $part)) {
343 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

343
                $text .= \chr(/** @scrutinizer ignore-type */ octdec(trim($part, '\\')));
Loading history...
344
            } else {
345 42
                $text .= $part;
346
            }
347
        }
348
349 42
        return $text;
350
    }
351
352
    /**
353
     * Decode string with html entity encoded chars.
354
     */
355 56
    public static function decodeEntities(string $text): string
356
    {
357 56
        $parts = preg_split('/(#\d{2})/s', $text, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE);
358 56
        $text = '';
359
360 56
        foreach ($parts as $part) {
361 56
            if (preg_match('/^#\d{2}$/', $part)) {
362 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

362
                $text .= \chr(/** @scrutinizer ignore-type */ hexdec(trim($part, '#')));
Loading history...
363
            } else {
364 56
                $text .= $part;
365
            }
366
        }
367
368 56
        return $text;
369
    }
370
371
    /**
372
     * Check if given string is Unicode text (by BOM);
373
     * If true - decode to "utf-8" encoded string.
374
     * Otherwise - return text as is.
375
     *
376
     * @todo Rename in next major release to make the name correspond to reality (for ex. decodeIfUnicode())
377
     */
378 42
    public static function decodeUnicode(string $text): string
379
    {
380 42
        if (preg_match('/^\xFE\xFF/i', $text)) {
381
            // Strip U+FEFF byte order marker.
382 26
            $decode = substr($text, 2);
383 26
            $text = '';
384 26
            $length = \strlen($decode);
385
386 26
            for ($i = 0; $i < $length; $i += 2) {
387 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

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

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

496
                        $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...
497
                    } else {
498
                        $fonts = $this->get('DescendantFonts')->getContent();
499
                    }
500
                    $decoded = false;
501
502
                    foreach ($fonts as $font) {
503
                        if ($font instanceof self) {
504
                            if (false !== ($decoded = $font->translateChar($char, false))) {
505
                                $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

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

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