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