Completed
Push — master ( 04aca3...4b3d1a )
by
unknown
03:17
created

ReservedAttributeNameConverter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 48
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A normalize() 0 12 3
A denormalize() 0 12 3
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\JsonApi\Serializer;
15
16
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
17
18
/**
19
 * Reserved attribute name converter.
20
 *
21
 * @author Baptiste Meyer <[email protected]>
22
 */
23
final class ReservedAttributeNameConverter implements NameConverterInterface
24
{
25
    const JSON_API_RESERVED_ATTRIBUTES = [
26
        'id' => '_id',
27
        'type' => '_type',
28
        'links' => '_links',
29
        'relationships' => '_relationships',
30
    ];
31
32
    private $nameConverter;
33
34
    public function __construct(NameConverterInterface $nameConverter = null)
35
    {
36
        $this->nameConverter = $nameConverter;
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function normalize($propertyName)
43
    {
44
        if (null !== $this->nameConverter) {
45
            $propertyName = $this->nameConverter->normalize($propertyName);
46
        }
47
48
        if (isset(self::JSON_API_RESERVED_ATTRIBUTES[$propertyName])) {
49
            $propertyName = self::JSON_API_RESERVED_ATTRIBUTES[$propertyName];
50
        }
51
52
        return $propertyName;
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function denormalize($propertyName)
59
    {
60
        if (in_array($propertyName, self::JSON_API_RESERVED_ATTRIBUTES, true)) {
61
            $propertyName = substr($propertyName, 1);
62
        }
63
64
        if (null !== $this->nameConverter) {
65
            $propertyName = $this->nameConverter->denormalize($propertyName);
66
        }
67
68
        return $propertyName;
69
    }
70
}
71