Passed
Push — dev ( 40f0b5...3a2e98 )
by Fike
02:50
created

Normalizer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
c 0
b 0
f 0
rs 10
cc 1
eloc 1
nc 1
nop 1
1
<?php
2
3
namespace AmaTeam\ElasticSearch\Indexing;
4
5
use AmaTeam\ElasticSearch\API\Indexing;
6
use AmaTeam\ElasticSearch\API\Indexing\AnalysisInterface;
7
use AmaTeam\ElasticSearch\API\Indexing\Normalization\Context;
8
use AmaTeam\ElasticSearch\API\Indexing\Normalization\ContextInterface;
9
use AmaTeam\ElasticSearch\API\Indexing\NormalizerInterface;
10
use AmaTeam\ElasticSearch\API\IndexingInterface;
11
use AmaTeam\ElasticSearch\Indexing\Option\Infrastructure\Registry;
12
13
class Normalizer implements NormalizerInterface
14
{
15
    /**
16
     * @var Registry
17
     */
18
    private $optionRegistry;
19
20
    /**
21
     * @param Registry $optionRegistry
22
     */
23
    public function __construct(Registry $optionRegistry = null)
24
    {
25
        $this->optionRegistry = $optionRegistry ?? Registry::getInstance();
26
    }
27
28
    public function normalize(IndexingInterface $indexing, ContextInterface $context = null): IndexingInterface
29
    {
30
        $context = $context ?? new Context();
31
        return (new Indexing())
32
            ->setType($indexing->getType())
33
            ->setWriteIndices(array_unique($indexing->getWriteIndices()))
34
            ->setReadIndices(array_unique($indexing->getReadIndices()))
35
            ->setAnalysis($this->normalizeAnalysis($indexing->getAnalysis(), $context))
36
            ->setOptions($this->normalizeOptions($indexing->getOptions(), $context));
37
    }
38
39
    private function normalizeAnalysis(AnalysisInterface $analysis, ContextInterface $context): AnalysisInterface
40
    {
41
        // TODO
42
        // silencing complexity analyser
43
        return $context ? $analysis : $analysis;
44
    }
45
46
    private function normalizeOptions(array $options, ContextInterface $context): array
47
    {
48
        $result = [];
49
        foreach ($options as $name => $value) {
50
            $option = $this->optionRegistry->find($name);
51
            if ($option) {
52
                if ($value !== null || $option->allowsNullValue()) {
53
                    $result[$option->getId()] = $value;
54
                }
55
                continue;
56
            }
57
            if ($context->shouldPreserveUnknownOptions() || in_array($name, $context->getPreservedOptions())) {
58
                $result[$name] = $value;
59
            }
60
        }
61
        return $result;
62
    }
63
}
64