]> Raphaël G. Git Repositories - packbundle/blob - Util/SluggerUtil.php
Switch to kernel.secret like documented in symfony example
[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 * Helps manage string conversions
16 */
17 class SluggerUtil {
18 //The secret parameter
19 private $secret;
20
21 //The alpha array
22 private $alpha;
23
24 //The rev array
25 private $rev;
26
27 //The alpha array key number
28 private $count;
29
30 //The offset reduced from secret
31 private $offset;
32
33 /**
34 * Creates a new slugger util
35 *
36 * @todo Add a command to generate alpha array or generate it on first run with cache storage ?
37 * @todo Use Cache like in calendar controller through FilesystemAdapter
38 *
39 * @param string $secret The secret string
40 */
41 public function __construct(string $secret) {
42 //Set secret
43 $this->secret = $secret;
44
45 //Pseudo-random alphabet
46 //XXX: use array flip and keys to workaround php "smart" that cast range('0', '9') as int instead of string
47 //XXX: The key count mismatch, count(alpha)>count(rev), resulted in a data corruption due to duplicate numeric values
48 $this->alpha = array_keys(array_flip(array_merge(
49 range('^', '[', -1),
50 range('V', 'Z'),
51 range('9', '7', -1),
52 range('L', 'O'),
53 range('f', 'a', -1),
54 range('_', '`'),
55 range('3', '0', -1),
56 range('E', 'H'),
57 range('v', 'r', -1),
58 range('+', '/'),
59 range('K', 'I', -1),
60 range('g', 'j'),
61 range('=', ':', -1),
62 range('>', '@'),
63 range('m', 'k', -1),
64 range('4', '6'),
65 range('*', '%', -1),
66 range('n', 'q'),
67 range('U', 'P', -1),
68 range(' ', '$'),
69 range('D', 'A', -1),
70 range('w', 'z'),
71 range('~', '!', -1)
72 )));
73
74 //Init rev array
75 $this->count = count($rev = $this->rev = array_flip($this->alpha));
76
77 //Init split
78 $split = str_split($this->secret);
79
80 //Set offset
81 $this->offset = array_reduce($split, function ($res, $a) use ($rev) { return $res += $rev[$a]; }, count($split)) % $this->count;
82 }
83
84 /**
85 * Flatten recursively an array
86 *
87 * @param array|string $data The data tree
88 * @param string|null $current The current prefix
89 * @param string $sep The key separator
90 * @param string $prefix The key prefix
91 * @param string $suffix The key suffix
92 * @return array The flattened data
93 */
94 public function flatten($data, ?string $current = null, string $sep = '.', string $prefix = '', string $suffix = ''): array {
95 //Init result
96 $ret = [];
97
98 //Look for data array
99 if (is_array($data)) {
100 //Iteare on each pair
101 foreach($data as $k => $v) {
102 //Merge flattened value in return array
103 $ret += $this->flatten($v, empty($current) ? $k : $current.$sep.$k, $sep, $prefix, $suffix);
104 }
105 //Look flat data
106 } else {
107 //Store data in flattened key
108 $ret[$prefix.$current.$suffix] = $data;
109 }
110
111 //Return result
112 return $ret;
113 }
114
115 /**
116 * Crypt and base64uri encode string
117 *
118 * @param string $data The data string
119 * @return string The hashed data
120 */
121 public function hash(string $data): string {
122 //Return hashed data
123 //XXX: we use hash_hmac with md5 hash
124 //XXX: crypt was dropped because it provided identical signature for string starting with same pattern
125 return str_replace(['+','/'], ['-','_'], base64_encode(hash_hmac('md5', $data, $this->secret, true)));
126 }
127
128 /**
129 * Serialize then short
130 *
131 * @param array $data The data array
132 * @return string The serialized and shorted data
133 */
134 public function serialize(array $data): string {
135 //Return shorted serialized data
136 return $this->short(serialize($data));
137 }
138
139 /**
140 * Short
141 *
142 * @param string $data The data string
143 * @return string The shorted data
144 */
145 public function short(string $data): string {
146 //Return string
147 $ret = '';
148
149 //Iterate on each character
150 foreach(str_split($data) as $k => $c) {
151 if (isset($this->rev[$c]) && isset($this->alpha[($this->rev[$c]+$this->offset)%$this->count])) {
152 //XXX: Remap char to an other one
153 $ret .= chr(($this->rev[$c] - $this->offset + $this->count) % $this->count);
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 //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 //Convert from utf-8 to ascii, replace quotes with space, remove non alphanumericseparator, replace separator with dash and trim dash
176 return trim(preg_replace('/[\/_|+ -]+/', '-', strtolower(preg_replace('/[^a-zA-Z0-9\/_|+ -]/', '', str_replace(['\'', '"'], ' ', iconv('UTF-8', 'ASCII//TRANSLIT', $data))))), '-');
177 }
178
179 /**
180 * Unshort then unserialize
181 *
182 * @param string $data The data string
183 * @return array The unshorted and unserialized data
184 */
185 public function unserialize(string $data): array {
186 //Return unshorted unserialized string
187 return unserialize($this->unshort($data));
188 }
189
190 /**
191 * Unshort
192 *
193 * @param string $data The data string
194 * @return string The unshorted data
195 */
196 public function unshort(string $data): string {
197 //Return string
198 $ret = '';
199
200 //Iterate on each character
201 foreach(str_split(base64_decode(str_replace(['-','_'], ['+','/'], $data))) as $c) {
202 //XXX: Reverse map char to an other one
203 $ret .= $this->alpha[(ord($c) + $this->offset) % $this->count];
204 }
205
206 //Send result
207 return $ret;
208 }
209 }