-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRot47Cipher.php
More file actions
104 lines (81 loc) · 2.19 KB
/
Copy pathRot47Cipher.php
File metadata and controls
104 lines (81 loc) · 2.19 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
98
99
100
101
102
103
104
<?php
/*
* This file is part of the core-library package.
*
* (c) 2022 WEBEWEB
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types = 1);
namespace WBW\Library\Common\Cipher;
use WBW\Library\Common\Helper\StringHelper;
/**
* ROT 47 cipher.
*
* @author webeweb <https://github.com/webeweb>
* @package WBW\Library\Common\Cipher
*/
class Rot47Cipher {
/**
* Alphabet.
*
* @return string[] Returns the alphabet.
*/
protected static function alphabet(): array {
$alphabet = [];
for ($i = 33; $i <= 126; ++$i) {
$alphabet[] = chr($i);
}
return $alphabet;
}
/**
* Decodes.
*
* @param string|null $str The string.
* @return string|null Returns the decoded string.
*/
public static function decode(?string $str): ?string {
return static::transform($str, true);
}
/**
* Encodes.
*
* @param string|null $str The string.
* @return string|null Returns the encoded string.
*/
public static function encode(?string $str): ?string {
return static::transform($str);
}
/**
* Transform.
*
* @param string|null $str The string.
* @param bool $reverse Reverse ?
* @return string|null Returns the transformed string.
*/
protected static function transform(?string $str, bool $reverse = false): ?string {
if (null === $str) {
return null;
}
$output = [];
$string = StringHelper::removeAccents($str);
$alphas = static::alphabet();
$rot = false === $reverse ? 47 : -47;
$out = false === $reverse ? 94 : -94;
for ($i = 0; $i < strlen($string); ++$i) {
$c = substr($string, $i, 1);
$p = array_search($c, $alphas);
if (false !== $p) {
$p += $rot;
if ($p < 0 || 94 < $p) {
$p -= $out;
}
// Rotate character
$c = $alphas[$p];
}
$output[] = $c;
}
return implode("", $output);
}
}