-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathToUnicodeCMap.php
More file actions
72 lines (59 loc) · 2.31 KB
/
Copy pathToUnicodeCMap.php
File metadata and controls
72 lines (59 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php declare(strict_types=1);
namespace PrinsFrank\PdfParser\Document\CMap\ToUnicode;
use PrinsFrank\PdfParser\Exception\InvalidArgumentException;
use PrinsFrank\PdfParser\Exception\PdfParserException;
class ToUnicodeCMap {
/** @var list<BFRange|BFChar> */
private readonly array $bfCharRangeInfo;
/** @var array<int, string|null> */
private array $charCache = [];
/**
* @no-named-arguments
*
* @param list<CodeSpaceRange> $codeSpaceRanges
* @param int<1, max> $byteSize
* @throws InvalidArgumentException
*/
public function __construct(
public readonly array $codeSpaceRanges,
public readonly int $byteSize,
BFRange|BFChar ...$bfCharRangeInfo,
) {
$this->bfCharRangeInfo = $bfCharRangeInfo;
if ($this->byteSize < 1) {
throw new InvalidArgumentException();
}
}
/** @throws PdfParserException */
public function textToUnicode(string $characterGroup): string {
$unicode = '';
$chunkSize = $this->byteSize * 2;
$nrOfChunks = strlen($characterGroup) / $chunkSize;
for ($i = 0; $i < $nrOfChunks; $i++) {
$unicode .= $this->charToUnicode((int) hexdec(substr($characterGroup, $i * $chunkSize, $chunkSize))) ?? '';
}
return $unicode;
}
/** @throws PdfParserException */
protected function charToUnicode(int $characterCode): ?string {
if (array_key_exists($characterCode, $this->charCache)) {
return $this->charCache[$characterCode];
}
$char = null;
foreach ($this->bfCharRangeInfo as $bfCharRangeInfo) {
if (!$bfCharRangeInfo->containsCharacterCode($characterCode)) {
continue;
}
if (($char = $bfCharRangeInfo->toUnicode($characterCode)) !== "\0") { // Some characters map to NULL in one BFRange and to an actual character in another
return $this->charCache[$characterCode] = $char;
}
}
if ($char === "\0") {
return $this->charCache[$characterCode] = $char; // Only return NULL when it is the only character this is mapped to
}
if ($characterCode === 0) {
return $this->charCache[$characterCode] = '';
}
return $this->charCache[$characterCode] = null;
}
}