1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace AmaTeam\ElasticSearch\Mapping; |
6
|
|
|
|
7
|
|
|
use AmaTeam\ElasticSearch\API\Mapping\Normalization\ContextInterface; |
8
|
|
|
use AmaTeam\ElasticSearch\API\Mapping\MappingInterface; |
9
|
|
|
use AmaTeam\ElasticSearch\API\Mapping\Normalization\DefaultContext; |
10
|
|
|
use AmaTeam\ElasticSearch\API\Mapping\NormalizerInterface; |
11
|
|
|
use AmaTeam\ElasticSearch\API\Mapping\Type\ParameterInterface; |
12
|
|
|
use AmaTeam\ElasticSearch\API\Mapping\Type\TypeInterface; |
13
|
|
|
use AmaTeam\ElasticSearch\Mapping\Type\Infrastructure\Registry; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @inheritDoc |
17
|
|
|
*/ |
18
|
|
|
class Normalizer implements NormalizerInterface |
19
|
|
|
{ |
20
|
|
|
public function normalize(MappingInterface $mapping, ContextInterface $context = null): MappingInterface |
21
|
|
|
{ |
22
|
|
|
$context = $context ?? new DefaultContext(); |
23
|
|
|
$target = new Mapping(); |
24
|
|
|
$registry = Registry::getInstance(); |
25
|
|
|
$target->setType($mapping->getType()); |
26
|
|
|
$type = $registry->find($mapping->getType()); |
27
|
|
|
$parameters = $this->processParameters($mapping->getParameters(), $type, $context); |
28
|
|
|
$target->setParameters($parameters); |
29
|
|
|
foreach ($mapping->getProperties() as $name => $property) { |
30
|
|
|
$path = array_merge($context->getPath(), [$name]); |
31
|
|
|
$context = DefaultContext::from($context)->setPath($path); |
32
|
|
|
$result = $this->normalize($property, $context); |
33
|
|
|
$target->setProperty($name, $result); |
34
|
|
|
} |
35
|
|
|
return $target; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
private function processParameters(array $parameters, TypeInterface $type, ContextInterface $context): array |
39
|
|
|
{ |
40
|
|
|
$target = []; |
41
|
|
|
foreach ($parameters as $name => $value) { |
42
|
|
|
$parameter = $this->getTypeParameter($name, $type); |
43
|
|
|
if ($parameter) { |
44
|
|
|
if ($value === null && !$parameter->nullValueAllowed()) { |
45
|
|
|
continue; |
46
|
|
|
} |
47
|
|
|
$target[$parameter->getId()] = $value; |
48
|
|
|
continue; |
49
|
|
|
} |
50
|
|
|
if (!$context->shouldRemoveUnknownParameters() || in_array($name, $context->getIgnoredParameters())) { |
51
|
|
|
$target[$name] = $value; |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
return $target; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
private function getTypeParameter(string $name, TypeInterface $type): ?ParameterInterface |
58
|
|
|
{ |
59
|
|
|
$name = strtolower($name); |
60
|
|
|
foreach ($type->getParameters() as $parameter) { |
61
|
|
|
if (strtolower($parameter->getId()) === $name || strtolower($parameter->getFriendlyId()) === $name) { |
62
|
|
|
return $parameter; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
return null; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|