]> Raphaël G. Git Repositories - packbundle/blob - Util/SluggerUtil.php
3b1e6b5406b2b0e8a9b40653e54b81f31fa1985c
[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 * @description Run "php 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 $range The shuffled range string
46 * @param string $secret The secret string
47 */
48 public function __construct(protected string $range, protected string $secret) {
49 /**
50 * Get pseuto-random alphabet by splitting range string
51 * TODO: see required range by json_encode result and short input (0->255 ???)
52 * XXX: The key count mismatch, count(alpha)>count(rev), resulted in a data corruption due to duplicate numeric values
53 */
54 $this->alpha = str_split($this->range);
55
56 //Init rev array
57 $this->count = count($rev = $this->rev = array_flip($this->alpha));
58
59 //Init split
60 $split = str_split($this->secret);
61
62 //Set offset
63 $this->offset = array_reduce($split, function ($res, $a) use ($rev) { return $res += $rev[$a]; }, count($split)) % $this->count;
64 }
65
66 /**
67 * Flatten recursively an array
68 *
69 * @param array|string $data The data tree
70 * @param string|null $current The current prefix
71 * @param string $sep The key separator
72 * @param string $prefix The key prefix
73 * @param string $suffix The key suffix
74 * @return array The flattened data
75 */
76 public function flatten($data, ?string $current = null, string $sep = '.', string $prefix = '', string $suffix = ''): array {
77 //Init result
78 $ret = [];
79
80 //Look for data array
81 if (is_array($data)) {
82 //Iteare on each pair
83 foreach($data as $k => $v) {
84 //Merge flattened value in return array
85 $ret += $this->flatten($v, empty($current) ? $k : $current.$sep.$k, $sep, $prefix, $suffix);
86 }
87 //Look flat data
88 } else {
89 //Store data in flattened key
90 $ret[$prefix.$current.$suffix] = $data;
91 }
92
93 //Return result
94 return $ret;
95 }
96
97 /**
98 * Crypt and base64uri encode string
99 *
100 * @param array|string $data The data string
101 * @return string The hashed data
102 */
103 public function hash(array|string $data): string {
104 //With array
105 if (is_array($data)) {
106 //Json encode array
107 $data = json_encode($data);
108 }
109
110 //Return hashed data
111 //XXX: we use hash_hmac with md5 hash
112 //XXX: crypt was dropped because it provided identical signature for string starting with same pattern
113 return str_replace(['+','/'], ['-','_'], base64_encode(hash_hmac('md5', $data, $this->secret, true)));
114 }
115
116 /**
117 * Serialize then short
118 *
119 * @param array $data The data array
120 * @return string The serialized and shorted data
121 */
122 public function serialize(array $data): string {
123 //Return shorted serialized data
124 //XXX: dropped serialize use to prevent short function from dropping utf-8 characters
125 return $this->short(json_encode($data));
126 }
127
128 /**
129 * Short
130 *
131 * @param string $data The data string
132 * @return string The shorted data
133 */
134 public function short(string $data): string {
135 //Return string
136 $ret = '';
137
138 //With data
139 if (!empty($data)) {
140 //Iterate on each character
141 foreach(str_split($data) as $k => $c) {
142 if (isset($this->rev[$c]) && isset($this->alpha[($this->rev[$c]+$this->offset)%$this->count])) {
143 //XXX: Remap char to an other one
144 $ret .= chr(($this->rev[$c] - $this->offset + $this->count) % $this->count);
145 } else {
146 throw new \RuntimeException(sprintf('Unable to retrieve character: %c', $c));
147 }
148 }
149 }
150
151 //Send result
152 return str_replace(['+','/','='], ['-','_',''], base64_encode($ret));
153 }
154
155 /**
156 * Convert string to safe slug
157 *
158 * @param string $data The data string
159 * @return ?string The slugged data
160 */
161 function slug(?string $data): ?string {
162 //With null
163 if ($data === null) {
164 //Return null
165 return $data;
166 }
167
168 //Use Transliterator if available
169 if (class_exists('Transliterator')) {
170 //Convert from any to latin, then to ascii and lowercase
171 $trans = \Transliterator::create('Any-Latin; Latin-ASCII; Lower()');
172 //Replace every non alphanumeric character by dash then trim dash
173 return trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $trans->transliterate($data)), '-');
174 }
175
176 //Convert from utf-8 to ascii, replace quotes with space, remove non alphanumericseparator, replace separator with dash and trim dash
177 return trim(preg_replace('/[\/_|+ -]+/', '-', strtolower(preg_replace('/[^a-zA-Z0-9\/_|+ -]/', '', str_replace(['\'', '"'], ' ', iconv('UTF-8', 'ASCII//TRANSLIT', $data))))), '-');
178 }
179
180 /**
181 * Convert string to latin
182 *
183 * @param string $data The data string
184 * @return ?string The slugged data
185 */
186 function latin(?string $data): ?string {
187 //With null
188 if ($data === null) {
189 //Return null
190 return $data;
191 }
192
193 //Use Transliterator if available
194 if (class_exists('Transliterator')) {
195 //Convert from any to latin, then to ascii and lowercase
196 $trans = \Transliterator::create('Any-Latin; Latin-ASCII');
197 //Replace every non alphanumeric character by dash then trim dash
198 return trim($trans->transliterate($data));
199 }
200
201 //Convert from utf-8 to ascii
202 return trim(iconv('UTF-8', 'ASCII//TRANSLIT', $data));
203 }
204
205 /**
206 * Unshort then unserialize
207 *
208 * @param string $data The data string
209 * @return array The unshorted and unserialized data
210 */
211 public function unserialize(string $data): array {
212 //Return unshorted unserialized string
213 return json_decode($this->unshort($data), true);
214 }
215
216 /**
217 * Unshort
218 *
219 * @param string $data The data string
220 * @return string The unshorted data
221 */
222 public function unshort(string $data): string {
223 //Return string
224 $ret = '';
225
226 //Iterate on each character
227 foreach(str_split(base64_decode(str_replace(['-','_'], ['+','/'], $data))) as $c) {
228 //XXX: Reverse map char to an other one
229 $ret .= $this->alpha[(ord($c) + $this->offset) % $this->count];
230 }
231
232 //Send result
233 return $ret;
234 }
235 }