1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the API Platform project. |
5
|
|
|
* |
6
|
|
|
* (c) Kévin Dunglas <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace ApiPlatform\Core\Serializer\NameConverter; |
13
|
|
|
|
14
|
|
|
use Symfony\Component\Serializer\NameConverter\NameConverterInterface; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* CamelCase to dashed name converter. |
18
|
|
|
* |
19
|
|
|
* Based on Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter. |
20
|
|
|
* |
21
|
|
|
* @author Kévin Dunglas <[email protected]> |
22
|
|
|
*/ |
23
|
|
|
class CamelCaseToDashedCaseNameConverter implements NameConverterInterface |
24
|
|
|
{ |
25
|
|
|
/** |
26
|
|
|
* @var array|null |
27
|
|
|
*/ |
28
|
|
|
private $attributes; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @var bool |
32
|
|
|
*/ |
33
|
|
|
private $lowerCamelCase; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param null|array $attributes The list of attributes to rename or null for all attributes |
37
|
|
|
* @param bool $lowerCamelCase Use lowerCamelCase style |
38
|
|
|
*/ |
39
|
|
|
public function __construct(array $attributes = null, $lowerCamelCase = true) |
40
|
|
|
{ |
41
|
|
|
$this->attributes = $attributes; |
42
|
|
|
$this->lowerCamelCase = $lowerCamelCase; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* {@inheritdoc} |
47
|
|
|
*/ |
48
|
|
|
public function normalize($propertyName) |
49
|
|
|
{ |
50
|
|
|
if (null === $this->attributes || in_array($propertyName, $this->attributes)) { |
51
|
|
|
$lcPropertyName = lcfirst($propertyName); |
52
|
|
|
$snakeCasedName = ''; |
53
|
|
|
|
54
|
|
|
$len = strlen($lcPropertyName); |
55
|
|
|
for ($i = 0; $i < $len; ++$i) { |
56
|
|
|
if (ctype_upper($lcPropertyName[$i])) { |
57
|
|
|
$snakeCasedName .= '-'.strtolower($lcPropertyName[$i]); |
58
|
|
|
} else { |
59
|
|
|
$snakeCasedName .= strtolower($lcPropertyName[$i]); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return $snakeCasedName; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $propertyName; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* {@inheritdoc} |
71
|
|
|
*/ |
72
|
|
|
public function denormalize($propertyName) |
73
|
|
|
{ |
74
|
|
|
$camelCasedName = preg_replace_callback('/(^|-|\.)+(.)/', function ($match) { |
75
|
|
|
return ('.' === $match[1] ? '-' : '').strtoupper($match[2]); |
76
|
|
|
}, $propertyName); |
77
|
|
|
|
78
|
|
|
if ($this->lowerCamelCase) { |
79
|
|
|
$camelCasedName = lcfirst($camelCasedName); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
if (null === $this->attributes || in_array($camelCasedName, $this->attributes)) { |
83
|
|
|
return $camelCasedName; |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
return $propertyName; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|