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

Normalizer   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 11
dl 0
loc 49
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A normalize() 0 9 1
A normalizeAnalysis() 0 5 2
B normalizeOptions() 0 16 7
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