-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyHelper.php
More file actions
95 lines (82 loc) · 2.7 KB
/
Copy pathKeyHelper.php
File metadata and controls
95 lines (82 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
declare(strict_types=1);
namespace Echron\DataTypes\Helper;
use Echron\DataTypes\Exception\InvalidKeyException;
class KeyHelper
{
/**
* @param string $key
* @param bool $allowSlash
* @param int $maxLength
* @return string
* @throws InvalidKeyException
* @deprecated
*/
public static function formatKey(string $key, bool $allowSlash = false, int $maxLength = 0): string
{
//TODO: only allow int?
// if (!is_string($key) && !is_int($key)) {
// if (is_array($key)) {
// throw new InvalidKeyException('Id must be int or string, `' . self::getObjectType($key) . '` given (' . json_encode($key) . ') (' . json_encode(debug_backtrace()) . ')');
// }
//
// throw new InvalidKeyException('Id must be int or string, `' . self::getObjectType($key) . '` given');
// }
// $id = iconv("UTF-8", "UTF-8//IGNORE", $id);
//$id = mb_convert_encoding($id, 'UTF-8', 'UTF-8');
//$id = mb_strtolower($id);
$key = str_replace([
'ë',
'é',
'è',
'ç',
'ò',
'�',
], [
'e',
'e',
'e',
'c',
'o',
'_',
], $key);
//Remove special characters (http://regexr.com/3cpha)
//Don't use \w as character group, it will allow special non utf-8 characters
$regex = '/([^a-z0-9]+)|(\_{2,})/mi';
if ($allowSlash) {
$regex = '/([^a-z0-9\/]+)|(\s{2,})|(\_{2,})|(\/{2,})/im';
}
// if ($allowWhiteSpace) {
// $regex = '/([^\w\s]+)|(\s{2,})|(\_{2,})/im';
// if ($allowSlash) {
// $regex = '/([^\w\s\/]+)|(\s{2,})|(\_{2,})|(\/{2,})/im';
// }
// }
$key = preg_replace($regex, '_', $key);
if (strlen($key) < 1) {
$ex = new InvalidKeyException('Id must be longer than 1 character');
echo $ex->getTraceAsString();
throw $ex;
}
$key = strtolower($key);
if ($maxLength > 0) {
$key = substr($key, 0, $maxLength);
}
//Remove leading or trailing slashes
return trim($key, '_');
//Remove multi underscores
// $code = preg_replace('!\s+!', ' ', $code);
// $code = trim($code);
// $code = str_replace(' ', '_', $code);
//return $key;
}
// private static function getObjectType($var): string
// {
// $type = gettype($var);
// if ($type === 'object') {
// $type = get_class($var);
// }
//
// return $type;
// }
}