1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of dimtrovich/db-dumper". |
5
|
|
|
* |
6
|
|
|
* (c) 2024 Dimitri Sitchet Tomkeu <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view |
9
|
|
|
* the LICENSE file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Dimtrovich\DbDumper; |
13
|
|
|
|
14
|
|
|
abstract class CaseConverter |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* The cache of dot-cased words. |
18
|
|
|
*/ |
19
|
|
|
protected static array $dotCache = []; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* The cache of snake-cased words. |
23
|
|
|
*/ |
24
|
|
|
protected static array $snakeCache = []; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Convert a string to dot notation. |
28
|
|
|
*/ |
29
|
|
|
public static function toDot(string $value): string |
30
|
|
|
{ |
31
|
|
|
$key = $value; |
32
|
|
|
|
33
|
|
|
if (isset(static::$dotCache[$key])) { |
34
|
|
|
return static::$dotCache[$key]; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
$value = self::toSnake($value); |
38
|
|
|
|
39
|
|
|
return static::$dotCache[$key] = str_replace('_', '.', $value); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Convert a string to snake case. |
44
|
|
|
*/ |
45
|
|
|
public static function toSnake(string $value): string |
46
|
|
|
{ |
47
|
|
|
$key = $value; |
48
|
|
|
|
49
|
|
|
if (isset(static::$snakeCache[$key])) { |
50
|
|
|
return static::$snakeCache[$key]; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
if (! ctype_lower($value)) { |
54
|
|
|
$value = preg_replace('/\s+/u', '', ucwords($value)); |
55
|
|
|
|
56
|
|
|
$value = strtolower(preg_replace('/(.)(?=[A-Z])/u', '$1_', $value)); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
if ($value === $key) { |
60
|
|
|
$value = str_replace(['-', '.'], '_', $value); // hack for kebab case and dot annotation |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return static::$snakeCache[$key] = $value; |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|