]> Raphaël G. Git Repositories - packbundle/blob - Util/SluggerUtil.php
Add captcha option
[packbundle] / Util / SluggerUtil.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys PackBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\PackBundle\Util;
13
14 /**
15 * Manages string conversions
16 */
17 class SluggerUtil {
18 /**
19 * The alpha array
20 */
21 protected array $alpha;
22
23 /**
24 * The rev array
25 */
26 protected array $rev;
27
28 /**
29 * The alpha array key number
30 */
31 protected int $count;
32
33 /**
34 * The offset reduced from secret
35 */
36 protected int $offset;
37
38 /**
39 * Construct slugger util
40 *
41 * Run "bin/console rapsyspack:range" to generate RAPSYSPACK_RANGE="ayl[...]z9w" range in .env.local
42 *
43 * @todo Use Cache like in calendar controller through FilesystemAdapter ?
44 *
45 * @param string $secret The secret string
46 */
47 public function __construct(protected string $secret) {
48 //Without range
49 if (empty($range = $_ENV['RAPSYSPACK_RANGE']) || $range === 'Ch4ng3m3!') {
50 //Protect member variable setup
51 return;
52 }
53
54 /**
55 * Get pseuto-random alphabet by splitting range string
56 * TODO: see required range by json_encode result and short input (0->255 ???)
57 * XXX: The key count mismatch, count(alpha)>count(rev), resulted in a data corruption due to duplicate numeric values
58 */
59 $this->alpha = str_split($range);
60
61 //Init rev array
62 $this->count = count($rev = $this->rev = array_flip($this->alpha));
63
64 //Init split
65 $split = str_split($this->secret);
66
67 //Set offset
68 //TODO: protect undefined index ?
69 $this->offset = array_reduce($split, function ($res, $a) use ($rev) { return $res += $rev[$a]; }, count($split)) % $this->count;
70 }
71
72 /**
73 * Flatten recursively an array
74 *
75 * @param array|string $data The data tree
76 * @param string|null $current The current prefix
77 * @param string $sep The key separator
78 * @param string $prefix The key prefix
79 * @param string $suffix The key suffix
80 * @return array The flattened data
81 */
82 public function flatten($data, ?string $current = null, string $sep = '.', string $prefix = '', string $suffix = ''): array {
83 //Init result
84 $ret = [];
85
86 //Look for data array
87 if (is_array($data)) {
88 //Iteare on each pair
89 foreach($data as $k => $v) {
90 //Merge flattened value in return array
91 $ret += $this->flatten($v, empty($current) ? $k : $current.$sep.$k, $sep, $prefix, $suffix);
92 }
93 //Look flat data
94 } else {
95 //Store data in flattened key
96 $ret[$prefix.$current.$suffix] = $data;
97 }
98
99 //Return result
100 return $ret;
101 }
102
103 /**
104 * Crypt and base64uri encode string
105 *
106 * @param array|string $data The data string
107 * @return string The hashed data
108 */
109 public function hash(array|string $data): string {
110 //With array
111 if (is_array($data)) {
112 //Json encode array
113 $data = json_encode($data);
114 }
115
116 //Return hashed data
117 //XXX: we use hash_hmac with md5 hash
118 //XXX: crypt was dropped because it provided identical signature for string starting with same pattern
119 return str_replace(['+','/'], ['-','_'], base64_encode(hash_hmac('md5', $data, $this->secret, true)));
120 }
121
122 /**
123 * Serialize then short
124 *
125 * @param array $data The data array
126 * @return string The serialized and shorted data
127 */
128 public function serialize(array $data): string {
129 //Return shorted serialized data
130 //XXX: dropped serialize use to prevent short function from dropping utf-8 characters
131 return $this->short(json_encode($data));
132 }
133
134 /**
135 * Short
136 *
137 * @param string $data The data string
138 * @return string The shorted data
139 */
140 public function short(string $data): string {
141 //Return string
142 $ret = '';
143
144 //With data
145 if (!empty($data)) {
146 //Iterate on each character
147 foreach(str_split($data) as $k => $c) {
148 if (isset($this->rev[$c]) && isset($this->alpha[($this->rev[$c]+$this->offset)%$this->count])) {
149 //XXX: Remap char to an other one
150 $ret .= chr(($this->rev[$c] - $this->offset + $this->count) % $this->count);
151 } else {
152 throw new \RuntimeException(sprintf('Unable to retrieve character: %c', $c));
153 }
154 }
155 }
156
157 //Send result
158 return str_replace(['+','/','='], ['-','_',''], base64_encode($ret));
159 }
160
161 /**
162 * Convert string to safe slug
163 *
164 * @param string $data The data string
165 * @return ?string The slugged data
166 */
167 function slug(?string $data): ?string {
168 //With null
169 if ($data === null) {
170 //Return null
171 return $data;
172 }
173
174 //Use Transliterator if available
175 if (class_exists('Transliterator')) {
176 //Convert from any to latin, then to ascii and lowercase
177 $trans = \Transliterator::create('Any-Latin; Latin-ASCII; Lower()');
178 //Replace every non alphanumeric character by dash then trim dash
179 return trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $trans->transliterate($data)), '-');
180 }
181
182 //Convert from utf-8 to ascii, replace quotes with space, remove non alphanumericseparator, replace separator with dash and trim dash
183 return trim(preg_replace('/[\/_|+ -]+/', '-', strtolower(preg_replace('/[^a-zA-Z0-9\/_|+ -]/', '', str_replace(['\'', '"'], ' ', iconv('UTF-8', 'ASCII//TRANSLIT', $data))))), '-');
184 }
185
186 /**
187 * Convert string to latin
188 *
189 * @param string $data The data string
190 * @return ?string The slugged data
191 */
192 function latin(?string $data): ?string {
193 //With null
194 if ($data === null) {
195 //Return null
196 return $data;
197 }
198
199 //Use Transliterator if available
200 if (class_exists('Transliterator')) {
201 //Convert from any to latin, then to ascii and lowercase
202 $trans = \Transliterator::create('Any-Latin; Latin-ASCII');
203 //Replace every non alphanumeric character by dash then trim dash
204 return trim($trans->transliterate($data));
205 }
206
207 //Convert from utf-8 to ascii
208 return trim(iconv('UTF-8', 'ASCII//TRANSLIT', $data));
209 }
210
211 /**
212 * Unshort then unserialize
213 *
214 * @param string $data The data string
215 * @return array The unshorted and unserialized data
216 */
217 public function unserialize(string $data): array {
218 //Return unshorted unserialized string
219 return json_decode($this->unshort($data), true);
220 }
221
222 /**
223 * Unshort
224 *
225 * @param string $data The data string
226 * @return string The unshorted data
227 */
228 public function unshort(string $data): string {
229 //Return string
230 $ret = '';
231
232 //Iterate on each character
233 foreach(str_split(base64_decode(str_replace(['-','_'], ['+','/'], $data))) as $c) {
234 //XXX: Reverse map char to an other one
235 $ret .= $this->alpha[(ord($c) + $this->offset) % $this->count];
236 }
237
238 //Send result
239 return $ret;
240 }
241 }