-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathTransformUtils.php
82 lines (72 loc) · 1.95 KB
/
TransformUtils.php
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
<?php
declare(strict_types=1);
namespace ClassTransformer;
use function ucfirst;
use function ucwords;
use function lcfirst;
use function is_string;
use function strtolower;
use function preg_match;
use function str_replace;
use function preg_replace;
/**
*
*/
final class TransformUtils
{
/** @var array<string> */
private static array $camelCache = [];
/** @var array<string> */
private static array $snakeCache = [];
/** @var array<string> */
private static array $mutationSetterCache = [];
/**
* @param string $key
*
* @return string
*/
public static function attributeToSnakeCase(string $key): string
{
if (isset(self::$snakeCache[$key])) {
return self::$snakeCache[$key];
}
$str = preg_replace('/(?<=\d)(?=[A-Za-z])|(?<=[A-Za-z])(?=\d)|(?<=[a-z])(?=[A-Z])/', '_', $key) ?? '';
return self::$snakeCache[$key] = strtolower($str);
}
/**
* @param string $key
*
* @return string
*/
public static function attributeToCamelCase(string $key): string
{
if (isset(self::$camelCache[$key])) {
return self::$camelCache[$key];
}
$str = lcfirst(str_replace('_', '', ucwords($key, '_')));
return self::$camelCache[$key] = $str;
}
/**
* @param string $key
*
* @return string
*/
public static function mutationSetterToCamelCase(string $key): string
{
if (isset(self::$mutationSetterCache[$key])) {
return self::$mutationSetterCache[$key];
}
$str = 'set' . ucfirst(self::attributeToCamelCase($key)) . 'Attribute';
return self::$mutationSetterCache[$key] = $str;
}
/**
* @param string $phpDoc
*
* @return string|null
*/
public static function getClassFromPhpDoc(string $phpDoc): ?string
{
preg_match('/array<([a-zA-Z\d\\\]+)>/', $phpDoc, $arrayType);
return $arrayType[1] ?? null;
}
}