Completed
Pull Request — master (#869)
by
unknown
03:07 queued 01:21
created

MappingPass::handleDirectoryMapping()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 67

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 67
rs 7.7866
c 0
b 0
f 0
cc 7
nc 5
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[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
namespace ONGR\ElasticsearchBundle\DependencyInjection\Compiler;
13
14
use ONGR\ElasticsearchBundle\Annotation\Index;
15
use ONGR\ElasticsearchBundle\DependencyInjection\Configuration;
16
use ONGR\ElasticsearchBundle\Mapping\Converter;
17
use ONGR\ElasticsearchBundle\Mapping\DocumentParser;
18
use ONGR\ElasticsearchBundle\Mapping\IndexSettings;
19
use ONGR\ElasticsearchBundle\Service\IndexService;
20
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
21
use Symfony\Component\DependencyInjection\ContainerBuilder;
22
use Symfony\Component\DependencyInjection\Definition;
23
24
class MappingPass implements CompilerPassInterface
25
{
26
    /**
27
     * @var array
28
     */
29
    private $indexes = [];
30
31
    /**
32
     * @var string
33
     */
34
    private $defaultIndex = null;
35
36
    public function process(ContainerBuilder $container)
37
    {
38
        $kernelDir = $container->getParameter('kernel.project_dir');
39
40
        foreach ($container->getParameter(Configuration::ONGR_SOURCE_DIR) as $dir) {
41
            $this->handleDirectoryMapping($container, $kernelDir . $dir);
42
        }
43
44
        $container->setParameter(Configuration::ONGR_INDEXES, $this->indexes);
45
        $container->setParameter(
46
            Configuration::ONGR_DEFAULT_INDEX,
47
            $this->defaultIndex ?? current(array_keys($this->indexes))
48
        );
49
    }
50
51
    /**
52
     * @param ContainerBuilder $container
53
     * @param string $dir
54
     *
55
     * @throws \ReflectionException
56
     */
57
    private function handleDirectoryMapping(ContainerBuilder $container, string $dir): void
58
    {
59
        /** @var DocumentParser $parser */
60
        $parser = $container->get(DocumentParser::class);
61
        $indexesOverride = $container->getParameter(Configuration::ONGR_INDEXES_OVERRIDE);
62
63
        foreach ($this->getNamespaces($dir) as $namespace) {
64
            $class = new \ReflectionClass($namespace);
65
            /** @var Index $document */
66
            $document = $parser->getIndexAnnotation($class);
67
            $indexMapping = $parser->getIndexMetadata($class);
68
            $indexAlias = $parser->getIndexAliasName($class);
69
            $indexMetadata = $parser->getIndexMetadata($class);
70
71
            if (!empty($indexMapping)) {
72
                $indexMetadata['settings'] = array_filter(array_merge_recursive(
73
                    $indexMetadata['settings'] ?? [],
74
                    [
75
                        'number_of_replicas' => $document->numberOfReplicas,
76
                        'number_of_shards' => $document->numberOfShards,
77
                    ],
78
                    $indexesOverride[$namespace]['settings'] ?? []
79
                ));
80
81
                $indexSettings = new Definition(
82
                    IndexSettings::class,
83
                    [
84
                        $namespace,
85
                        $indexAlias,
86
                        $indexAlias,
87
                        $indexMetadata,
88
                        $indexesOverride[$namespace]['hosts'] ?? $document->hosts,
89
                        $indexesOverride[$namespace]['default'] ?? $document->default,
90
                        $indexesOverride[$namespace]['type'] ?? $document->typeName
0 ignored issues
show
Deprecated Code introduced by
The property ONGR\ElasticsearchBundle...tation\Index::$typeName has been deprecated with message: will be removed in v7 since there will be no more types in the indexes.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
91
                    ]
92
                );
93
94
                $indexServiceDefinition = new Definition(IndexService::class, [
95
                    $namespace,
96
                    $container->getDefinition(Converter::class),
97
                    $container->getDefinition('event_dispatcher'),
98
                    $container->getDefinition('serializer'),
99
                    $indexSettings,
100
                    $container->getParameter(Configuration::ONGR_PROFILER_CONFIG)
101
                        ? $container->getDefinition('ongr.esb.tracer') : null
102
                ]);
103
                $indexServiceDefinition->setPublic(true);
104
105
                $container->setDefinition($namespace, $indexServiceDefinition);
106
                $this->indexes[$indexAlias] = $namespace;
107
                $isCurrentIndexDefault = $parser->isDefaultIndex($class);
108
                if ($this->defaultIndex && $isCurrentIndexDefault) {
109
                    throw new \RuntimeException(
110
                        sprintf(
111
                            'Only one index can be set as default. We found 2 indexes as default ones `%s` and `%s`',
112
                            $this->defaultIndex,
113
                            $indexAlias
114
                        )
115
                    );
116
                }
117
118
                if ($isCurrentIndexDefault) {
119
                    $this->defaultIndex = $indexAlias;
120
                }
121
            }
122
        }
123
    }
124
125
    private function getNamespaces($directory): array
126
    {
127
        if (!is_dir($directory)) {
128
            return [];
129
        }
130
131
        $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory));
132
        $files = new \RegexIterator($iterator, '/^.+\.php$/i', \RecursiveRegexIterator::GET_MATCH);
133
134
        $documents = [];
135
136
        foreach ($files as $file => $v) {
137
            $documents[] = $this->getFullNamespace($file) . '\\' . $this->getClassname($file);
138
        }
139
140
        return $documents;
141
    }
142
143
    private function getFullNamespace($filename)
144
    {
145
        $lines = preg_grep('/^namespace /', file($filename));
146
        $namespaceLine = array_shift($lines);
147
        $match = array();
148
        preg_match('/^namespace (.*);$/', $namespaceLine, $match);
149
        $fullNamespace = array_pop($match);
150
151
        return $fullNamespace;
152
    }
153
154
    private function getClassname($filename)
155
    {
156
        $directoriesAndFilename = explode('/', $filename);
157
        $filename = array_pop($directoriesAndFilename);
158
        $nameAndExtension = explode('.', $filename);
159
        $className = array_shift($nameAndExtension);
160
161
        return $className;
162
    }
163
}
164