-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvisibleWrapper.php
More file actions
97 lines (83 loc) · 2.55 KB
/
InvisibleWrapper.php
File metadata and controls
97 lines (83 loc) · 2.55 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
class InvisibleWrapper
{
// Invisible characters used for encoding
const INVISIBLE_CHARACTERS = ["\u{200C}", "\u{200D}"];
const MESSAGE_END = "\x0A";
/**
* Converts string to byte array
*
* @param string $text The text to convert to bytes
* @return array Array of bytes
*/
private function toBytes($text)
{
// PHP equivalent of TextEncoder.encode
return array_values(unpack('C*', $text));
}
/**
* Pads binary string to 8 bits
*
* @param string $binary The binary string to pad
* @return string Padded binary string
*/
private function padToWholeBytes($binary)
{
$needsToAdd = 8 - strlen($binary);
return str_repeat('0', $needsToAdd) . $binary;
}
/**
* Encodes text to invisible characters
*
* @param string $text The text to encode
* @return string Text encoded with invisible characters
*/
public function encodeMessage($text)
{
// Convert text to bytes
$bytes = $this->toBytes($text);
// Convert bytes to binary string with padding and separator
$binary = '';
foreach ($bytes as $byte) {
$binary .= $this->padToWholeBytes(decbin($byte)) . '0';
}
// Convert binary to invisible characters
$result = '';
for ($i = 0; $i < strlen($binary); $i++) {
$result .= self::INVISIBLE_CHARACTERS[(int)$binary[$i]];
}
return $result;
}
/**
* Encodes a message with separator
*
* @param string $message The message to encode
* @return string Encoded message with separator
*/
function encodeWithSeparator($message)
{
return self::encodeMessage($message . self::MESSAGE_END);
}
/**
* Wraps a translation with invisible encoded key data
*
* @param string $key The translation key
* @param string|null $ns The namespace (optional)
* @param string $translation The translated text
* @return string Translation with appended invisible characters
*/
function wrapWithFullKeyEncode($key, $ns, $translation)
{
// Create the data structure to encode
$data = [
'k' => $key,
'n' => $ns ?: ''
];
// Convert to JSON
$encodedValue = json_encode($data);
// Encode with invisible characters
$invisibleMark = self::encodeWithSeparator($encodedValue);
// Append invisible characters to the translation
return $translation . $invisibleMark;
}
}