Passed
Pull Request — master (#1999)
by
unknown
03:15
created

InnerFieldsNameConverter::convertInnerFields()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 9
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 2
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\Bridge\Elasticsearch\Serializer\NameConverter;
15
16
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
17
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
18
19
/**
20
 * Converts inner fields with a decorated name converter.
21
 *
22
 * @experimental
23
 *
24
 * @author Baptiste Meyer <[email protected]>
25
 */
26
final class InnerFieldsNameConverter implements NameConverterInterface
27
{
28
    private $decorated;
29
30
    public function __construct(?NameConverterInterface $decorated = null)
31
    {
32
        $this->decorated = $decorated ?? new CamelCaseToSnakeCaseNameConverter();
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public function normalize($propertyName)
39
    {
40
        return $this->convertInnerFields($propertyName, true);
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function denormalize($propertyName)
47
    {
48
        return $this->convertInnerFields($propertyName, false);
49
    }
50
51
    private function convertInnerFields(string $propertyName, bool $normalization): string
52
    {
53
        $convertedProperties = [];
54
55
        foreach (explode('.', $propertyName) as $decomposedProperty) {
56
            $convertedProperties[] = $this->decorated->{$normalization ? 'normalize' : 'denormalize'}($decomposedProperty);
57
        }
58
59
        return implode('.', $convertedProperties);
60
    }
61
}
62