Completed
Push — master ( a2eaba...a27a4d )
by Simonas
14:46 queued 08:23
created

MappingPass::handleDirectoryMapping()   C

Complexity

Conditions 9
Paths 9

Size

Total Lines 79

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 79
rs 6.9026
c 0
b 0
f 0
cc 9
nc 9
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
        $converterDefinition = $container->getDefinition(Converter::class);
63
64
        foreach ($this->getNamespaces($dir) as $namespace) {
65
            $class = new \ReflectionClass($namespace);
66
67
            if (isset($indexesOverride[$namespace]['alias']) && $indexesOverride[$namespace]['alias']) {
68
                $indexAlias = $indexesOverride[$namespace]['alias'];
69
            } else {
70
                $indexAlias = $parser->getIndexAliasName($class);
71
            }
72
73
            /** @var Index $document */
74
            $document = $parser->getIndexAnnotation($class);
75
            $indexMetadata = $parser->getIndexMetadata($class);
76
77
            if (!empty($indexMetadata)) {
78
                $indexMetadata['settings'] = array_filter(array_merge_recursive(
79
                    $indexMetadata['settings'] ?? [],
80
                    [
81
                        'number_of_replicas' => $document->numberOfReplicas,
82
                        'number_of_shards' => $document->numberOfShards,
83
                    ],
84
                    $indexesOverride[$namespace]['settings'] ?? []
85
                ));
86
87
                $indexSettings = new Definition(
88
                    IndexSettings::class,
89
                    [
90
                        $namespace,
91
                        $indexAlias,
92
                        $indexAlias,
93
                        $indexMetadata,
94
                        $indexesOverride[$namespace]['hosts'] ?? $document->hosts,
95
                        $indexesOverride[$namespace]['default'] ?? $document->default,
96
                        $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...
97
                    ]
98
                );
99
100
                $indexServiceDefinition = new Definition(IndexService::class, [
101
                    $namespace,
102
                    $converterDefinition,
103
                    $container->getDefinition('event_dispatcher'),
104
                    $indexSettings,
105
                    $container->getParameter(Configuration::ONGR_PROFILER_CONFIG)
106
                        ? $container->getDefinition('ongr.esb.tracer') : null
107
                ]);
108
                $indexServiceDefinition->setPublic(true);
109
                $converterDefinition->addMethodCall(
110
                    'addClassMetadata',
111
                    [
112
                        $namespace,
113
                        $parser->getPropertyMetadata($class)
114
                    ]
115
                );
116
117
                $container->setDefinition($namespace, $indexServiceDefinition);
118
                $this->indexes[$indexAlias] = $namespace;
119
                $isCurrentIndexDefault = $parser->isDefaultIndex($class);
120
                if ($this->defaultIndex && $isCurrentIndexDefault) {
121
                    throw new \RuntimeException(
122
                        sprintf(
123
                            'Only one index can be set as default. We found 2 indexes as default ones `%s` and `%s`',
124
                            $this->defaultIndex,
125
                            $indexAlias
126
                        )
127
                    );
128
                }
129
130
                if ($isCurrentIndexDefault) {
131
                    $this->defaultIndex = $indexAlias;
132
                }
133
            }
134
        }
135
    }
136
137
    private function getNamespaces($directory): array
138
    {
139
        if (!is_dir($directory)) {
140
            return [];
141
        }
142
143
        $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory));
144
        $files = new \RegexIterator($iterator, '/^.+\.php$/i', \RecursiveRegexIterator::GET_MATCH);
145
146
        $documents = [];
147
148
        foreach ($files as $file => $v) {
149
            $documents[] = $this->getFullNamespace($file) . '\\' . $this->getClassname($file);
150
        }
151
152
        return $documents;
153
    }
154
155
    private function getFullNamespace($filename)
156
    {
157
        $lines = preg_grep('/^namespace /', file($filename));
158
        $namespaceLine = array_shift($lines);
159
        $match = array();
160
        preg_match('/^namespace (.*);$/', $namespaceLine, $match);
161
        $fullNamespace = array_pop($match);
162
163
        return $fullNamespace;
164
    }
165
166
    private function getClassname($filename)
167
    {
168
        $directoriesAndFilename = explode('/', $filename);
169
        $filename = array_pop($directoriesAndFilename);
170
        $nameAndExtension = explode('.', $filename);
171
        $className = array_shift($nameAndExtension);
172
173
        return $className;
174
    }
175
}
176