forked from flix-tech/avro-serde-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AvroNameConverter.php
111 lines (89 loc) · 2.93 KB
/
AvroNameConverter.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php
declare(strict_types=1);
namespace FlixTech\AvroSerializer\Integrations\Symfony\Serializer\NameConverter;
use Exception;
use FlixTech\AvroSerializer\Integrations\Symfony\Serializer\AvroSerDeEncoder;
use FlixTech\AvroSerializer\Objects\Schema\AttributeName;
use FlixTech\AvroSerializer\Objects\Schema\Generation\SchemaAttributeReader;
use ReflectionClass;
use ReflectionProperty;
use Symfony\Component\Serializer\NameConverter\AdvancedNameConverterInterface;
if (!\interface_exists(AdvancedNameConverterInterface::class)) {
throw new Exception("The advanced name converter is supported only in symfony 4 and forward");
}
class AvroNameConverter implements AdvancedNameConverterInterface
{
/**
* @var SchemaAttributeReader
*/
private $attributeReader;
/**
* @var array<string, PropertyNameMap>
*/
private $mapCache = [];
public function __construct(SchemaAttributeReader $attributeReader)
{
$this->attributeReader = $attributeReader;
}
public function normalize(
$propertyName,
string $class = null,
string $format = null,
array $context = []
): string {
return $this
->getNameMap($class, $format)
->getNormalized($propertyName);
}
private function getNameMap(?string $class, ?string $format): PropertyNameMap
{
if (null === $class || !class_exists($class)) {
return new PropertyNameMap();
}
if (null === $format || AvroSerDeEncoder::FORMAT_AVRO !== $format) {
return new PropertyNameMap();
}
return $this->generateMap($class);
}
private function generateMap(string $class): PropertyNameMap
{
if (isset($this->mapCache[$class])) {
return $this->mapCache[$class];
}
$reflectionClass = new ReflectionClass($class);
$map = array_reduce(
$reflectionClass->getProperties(),
[$this, 'propertyToSchemaName'],
new PropertyNameMap()
);
$this->mapCache[$class] = $map;
return $map;
}
private function propertyToSchemaName(
PropertyNameMap $map,
ReflectionProperty $reflectionProperty
): PropertyNameMap {
$schemaAttributes = $this->attributeReader->readPropertyAttributes($reflectionProperty);
if (!$schemaAttributes->has(AttributeName::NAME)) {
return $map;
}
$attributeName = $schemaAttributes->get(AttributeName::NAME);
if (!is_string($attributeName)) {
return $map;
}
return $map->add(
$reflectionProperty->getName(),
$attributeName
);
}
public function denormalize(
$propertyName,
string $class = null,
string $format = null,
array $context = []
): string {
return $this
->getNameMap($class, $format)
->getDenormalized($propertyName);
}
}