]>
Raphaël G. Git Repositories - packbundle/blob - Util/SluggerUtil.php
1 <?php
declare(strict_types
=1);
4 * This file is part of the Rapsys PackBundle package.
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Rapsys\PackBundle\Util
;
15 * Manages string conversions
21 protected array $alpha;
29 * The alpha array key number
34 * The offset reduced from secret
36 protected int $offset;
39 * Construct slugger util
41 * @description Run "php bin/console rapsyspack:range" to generate RAPSYSPACK_RANGE="ayl[...]z9w" range in .env.local
43 * @todo Use Cache like in calendar controller through FilesystemAdapter ?
45 * @param string $range The shuffled range string
46 * @param string $secret The secret string
48 public function __construct(protected string $range, protected string $secret) {
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
54 $this->alpha
= str_split($this->range
);
57 $this->count
= count($rev = $this->rev
= array_flip($this->alpha
));
60 $split = str_split($this->secret
);
63 $this->offset
= array_reduce($split, function ($res, $a) use ($rev) { return $res +
= $rev
[$a
]; }, count($split)) %
$this->count
;
67 * Flatten recursively an array
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
76 public function flatten($data, ?string $current = null, string $sep = '.', string $prefix = '', string $suffix = ''): array {
81 if (is_array($data)) {
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);
89 //Store data in flattened key
90 $ret[$prefix.$current.$suffix] = $data;
98 * Crypt and base64uri encode string
100 * @param array|string $data The data string
101 * @return string The hashed data
103 public function hash(array|string $data): string {
105 if (is_array($data)) {
107 $data = json_encode($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)));
117 * Serialize then short
119 * @param array $data The data array
120 * @return string The serialized and shorted data
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));
131 * @param string $data The data string
132 * @return string The shorted data
134 public function short(string $data): string {
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
);
146 throw new \
RuntimeException(sprintf('Unable to retrieve character: %c', $c));
152 return str_replace(['+','/','='], ['-','_',''], base64_encode($ret));
156 * Convert string to safe slug
158 * @param string $data The data string
159 * @return ?string The slugged data
161 function slug(?string $data): ?string {
163 if ($data === null) {
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)), '-');
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))))), '-');
181 * Convert string to latin
183 * @param string $data The data string
184 * @return ?string The slugged data
186 function latin(?string $data): ?string {
188 if ($data === null) {
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));
201 //Convert from utf-8 to ascii
202 return trim(iconv('UTF-8', 'ASCII//TRANSLIT', $data));
206 * Unshort then unserialize
208 * @param string $data The data string
209 * @return array The unshorted and unserialized data
211 public function unserialize(string $data): array {
212 //Return unshorted unserialized string
213 return json_decode($this->unshort($data), true);
219 * @param string $data The data string
220 * @return string The unshorted data
222 public function unshort(string $data): string {
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
];