]> Raphaƫl G. Git Repositories - userbundle/blob - Utils/Slugger.php
Enable all fields by default
[userbundle] / Utils / Slugger.php
1 <?php
2
3 namespace Rapsys\UserBundle\Utils;
4
5 use Symfony\Component\DependencyInjection\ContainerInterface;
6
7 class Slugger {
8 //The secret parameter
9 private $secret;
10
11 //The alpha array
12 private $alpha;
13
14 //The rev array
15 private $rev;
16
17 //The alpha array key number
18 private $count;
19
20 //The offset reduced from secret
21 private $offset;
22
23 //Retrieve secret and set offset from reduction
24 public function __construct(ContainerInterface $container) {
25 //Set secret
26 $this->secret = $_SERVER['APP_SECRET'] ?? $container->getParameter('kernel.secret');
27
28 //Pseudo-random alphabet
29 //XXX: use array flip and keys to workaround php "smart" that cast range('0', '9') as int instead of string
30 //XXX: The key count mismatch, count(alpha)>count(rev), resulted in a data corruption due to duplicate numeric values
31 //TODO: set this as a parameter generated once in a command ?
32 $this->alpha = array_keys(array_flip(array_merge(
33 range('^', '[', -1),
34 range('V', 'Z'),
35 range('9', '7', -1),
36 range('L', 'O'),
37 range('f', 'a', -1),
38 range('_', '`'),
39 range('3', '0', -1),
40 range('E', 'H'),
41 range('v', 'r', -1),
42 range('+', '/'),
43 range('K', 'I', -1),
44 range('g', 'j'),
45 range('=', ':', -1),
46 range('>', '@'),
47 range('m', 'k', -1),
48 range('4', '6'),
49 range('*', '%', -1),
50 range('n', 'q'),
51 range('U', 'P', -1),
52 range(' ', '$'),
53 range('D', 'A', -1),
54 range('w', 'z'),
55 range('~', '!', -1)
56 )));
57
58 //Init rev array
59 $this->count = count($rev = $this->rev = array_flip($this->alpha));
60
61 //Init split
62 $split = str_split($this->secret);
63
64 //Set offset
65 $this->offset = array_reduce($split, function ($res, $a) use ($rev) { return $res += $rev[$a]; }, count($split)) % $this->count;
66 }
67
68 /**
69 * Flatten recursively an array
70 *
71 * @param array $data The data tree
72 * @param string|null $current The current prefix
73 * @param string $sep The key separator
74 * @param string $prefix The key prefix
75 * @param string $suffix The key suffix
76 * @return array The flattened data
77 */
78 public function flatten($data, $current = null, $sep = '.', $prefix = '', $suffix = '') {
79 //Init result
80 $ret = [];
81
82 //Look for data array
83 if (is_array($data)) {
84 //Iteare on each pair
85 foreach($data as $k => $v) {
86 //Merge flattened value in return array
87 $ret += $this->flatten($v, empty($current) ? $k : $current.$sep.$k, $sep, $prefix, $suffix);
88 }
89 //Look flat data
90 } else {
91 //Store data in flattened key
92 $ret[$prefix.$current.$suffix] = $data;
93 }
94
95 //Return result
96 return $ret;
97 }
98
99 /**
100 * Crypt and base64uri encode string
101 *
102 * @param string $data The data string
103 * @return string The hashed data
104 */
105 public function hash(string $data): string {
106 //Return hashed data
107 //XXX: we use hash_hmac with md5 hash
108 //XXX: crypt was dropped because it provided identical signature for string starting with same pattern
109 return str_replace(['+','/'], ['-','_'], base64_encode(hash_hmac('md5', $data, $this->secret, true)));
110 }
111
112 /**
113 * Serialize then short
114 *
115 * @param array $data The data array
116 * @return string The serialized and shorted data
117 */
118 public function serialize(array $data): string {
119 //Return shorted serialized data
120 return $this->short(serialize($data));
121 }
122
123 /**
124 * Short
125 *
126 * @param string $data The data string
127 * @return string The shorted data
128 */
129 public function short(string $data): string {
130 //Return string
131 $ret = '';
132
133 //Iterate on each character
134 foreach(str_split($data) as $k => $c) {
135 if (isset($this->rev[$c]) && isset($this->alpha[($this->rev[$c]+$this->offset)%$this->count])) {
136 //XXX: Remap char to an other one
137 $ret .= chr(($this->rev[$c] - $this->offset + $this->count) % $this->count);
138 }
139 }
140
141 //Send result
142 return str_replace(['+','/'], ['-','_'], base64_encode($ret));
143 }
144
145 /**
146 * Convert string to safe slug
147 *
148 * @param string $data The data string
149 * @return string The slugged data
150 */
151 function slug(string $data): string {
152 //Use Transliterator if available
153 if (class_exists('Transliterator')) {
154 $trans = \Transliterator::create('Any-Latin; Latin-ASCII; Lower()');
155 return preg_replace(['/[^a-zA-Z0-9]+/', '/(^-+|-+$)/'], ['-', ''], $trans->transliterate($data));
156 }
157 return preg_replace('/[\/_|+ -]+/', '-', strtolower(trim(preg_replace('/[^a-zA-Z0-9\/_|+ -]/', '', str_replace(['\'', '"'], ' ', iconv('UTF-8', 'ASCII//TRANSLIT', $data))), '-')));
158 }
159
160 /**
161 * Unshort then unserialize
162 *
163 * @param string $data The data string
164 * @return array The unshorted and unserialized data
165 */
166 public function unserialize(string $data): array {
167 //Return unshorted unserialized string
168 return unserialize($this->unshort($data));
169 }
170
171 /**
172 * Unshort
173 *
174 * @param string $data The data string
175 * @return string The unshorted data
176 */
177 public function unshort(string $data): string {
178 //Return string
179 $ret = '';
180
181 //Iterate on each character
182 foreach(str_split(base64_decode(str_replace(['-','_'], ['+','/'], $data))) as $c) {
183 //XXX: Reverse map char to an other one
184 $ret .= $this->alpha[(ord($c) + $this->offset) % $this->count];
185 }
186
187 //Send result
188 return $ret;
189 }
190 }