Completed
Pull Request — 6.1-dev (#889)
by
unknown
01:14
created

DocumentParser::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 3
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\Mapping;
13
14
use Doctrine\Common\Annotations\AnnotationRegistry;
15
use Doctrine\Common\Annotations\Reader;
16
use Doctrine\Common\Cache\Cache;
17
use ONGR\ElasticsearchBundle\Annotation\AbstractAnnotation;
18
use ONGR\ElasticsearchBundle\Annotation\Embedded;
19
use ONGR\ElasticsearchBundle\Annotation\Id;
20
use ONGR\ElasticsearchBundle\Annotation\Index;
21
use ONGR\ElasticsearchBundle\Annotation\NestedType;
22
use ONGR\ElasticsearchBundle\Annotation\ObjectType;
23
use ONGR\ElasticsearchBundle\Annotation\PropertiesAwareInterface;
24
use ONGR\ElasticsearchBundle\Annotation\Property;
25
use ONGR\ElasticsearchBundle\DependencyInjection\Configuration;
26
27
/**
28
 * Document parser used for reading document annotations.
29
 */
30
class DocumentParser
31
{
32
    const OBJ_CACHED_FIELDS = 'ongr.obj_fields';
33
    const EMBEDDED_CACHED_FIELDS = 'ongr.embedded_fields';
34
    const ARRAY_CACHED_FIELDS = 'ongr.array_fields';
35
36
    private $reader;
37
    private $properties = [];
38
    private $analysisConfig = [];
39
    private $cache;
40
41
    public function __construct(Reader $reader, Cache $cache, array $analysisConfig = [])
42
    {
43
        $this->reader = $reader;
44
        $this->cache = $cache;
45
        $this->analysisConfig = $analysisConfig;
46
47
        #Fix for annotations loader until doctrine/annotations 2.0 will be released with the full autoload support.
48
        AnnotationRegistry::registerLoader('class_exists');
0 ignored issues
show
Deprecated Code introduced by
The method Doctrine\Common\Annotati...istry::registerLoader() has been deprecated with message: this method is deprecated and will be removed in doctrine/annotations 2.0 autoloading should be deferred to the globally registered autoloader by then. For now, use @example AnnotationRegistry::registerLoader('class_exists')

This method 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 method will be removed from the class and what other method or class to use instead.

Loading history...
49
    }
50
51
    public function getIndexAliasName(\ReflectionClass $class): string
52
    {
53
        /** @var Index $document */
54
        $document = $this->reader->getClassAnnotation($class, Index::class);
55
56
        return $document->alias ?? Caser::snake($class->getShortName());
57
    }
58
59
    public function isDefaultIndex(\ReflectionClass $class): bool
60
    {
61
        /** @var Index $document */
62
        $document = $this->reader->getClassAnnotation($class, Index::class);
63
64
        return $document->default;
65
    }
66
67
    public function getIndexAnnotation(\ReflectionClass $class)
68
    {
69
        /** @var Index $document */
70
        $document = $this->reader->getClassAnnotation($class, Index::class);
71
72
        return $document;
73
    }
74
75
    /**
76
     * @deprecated will be deleted in v7. Types are deleted from elasticsearch.
77
     */
78
    public function getTypeName(\ReflectionClass $class): string
79
    {
80
        /** @var Index $document */
81
        $document = $this->reader->getClassAnnotation($class, Index::class);
82
83
        return $document->typeName ?? '_doc';
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...
84
    }
85
86
    public function getIndexMetadata(\ReflectionClass $class): array
87
    {
88
        if ($class->isTrait()) {
89
            return [];
90
        }
91
92
        /** @var Index $document */
93
        $document = $this->reader->getClassAnnotation($class, Index::class);
94
95
        if ($document === null) {
96
            return [];
97
        }
98
99
        $settings = $document->getSettings();
100
        $settings['analysis'] = $this->getAnalysisConfig($class);
101
102
        return array_filter(array_map('array_filter', [
103
            'settings' => $settings,
104
            'mappings' => [
105
                $this->getTypeName($class) => [
0 ignored issues
show
Deprecated Code introduced by
The method ONGR\ElasticsearchBundle...ntParser::getTypeName() has been deprecated with message: will be deleted in v7. Types are deleted from elasticsearch.

This method 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 method will be removed from the class and what other method or class to use instead.

Loading history...
106
                    'properties' => array_filter($this->getClassMetadata($class))
107
                ]
108
            ]
109
        ]));
110
    }
111
112
    public function getDocumentNamespace(string $indexAlias): ?string
113
    {
114
        if ($this->cache->contains(Configuration::ONGR_INDEXES)) {
115
            $indexes = $this->cache->fetch(Configuration::ONGR_INDEXES);
116
117
            if (isset($indexes[$indexAlias])) {
118
                return $indexes[$indexAlias];
119
            }
120
        }
121
122
        return null;
123
    }
124
125
    public function getParsedDocument(\ReflectionClass $class): Index
126
    {
127
        /** @var Index $document */
128
        $document = $this->reader->getClassAnnotation($class, Index::class);
129
130
        return $document;
131
    }
132
133
    private function getClassMetadata(\ReflectionClass $class): array
134
    {
135
        $mapping = [];
136
        $objFields = null;
137
        $arrayFields = null;
138
        $embeddedFields = null;
139
140
        /** @var \ReflectionProperty $property */
141
        foreach ($this->getDocumentPropertiesReflection($class) as $name => $property) {
142
            $annotations = $this->reader->getPropertyAnnotations($property);
143
144
            /** @var AbstractAnnotation $annotation */
145
            foreach ($annotations as $annotation) {
146
                if (!$annotation instanceof PropertiesAwareInterface) {
147
                    continue;
148
                }
149
150
                $fieldMapping = $annotation->getSettings();
151
152
                if ($annotation instanceof Property) {
153
                    $fieldMapping['type'] = $annotation->type;
154
                    $fieldMapping['analyzer'] = $annotation->analyzer;
155
                    $fieldMapping['search_analyzer'] = $annotation->searchAnalyzer;
156
                    $fieldMapping['search_quote_analyzer'] = $annotation->searchQuoteAnalyzer;
157
                }
158
159
                if ($annotation instanceof Embedded) {
160
                    $embeddedClass = new \ReflectionClass($annotation->class);
161
                    $fieldMapping['type'] = $this->getObjectMappingType($embeddedClass);
162
                    $fieldMapping['properties'] = $this->getClassMetadata($embeddedClass);
163
                    $embeddedFields[$name] = $annotation->class;
164
                }
165
166
                $mapping[$annotation->getName() ?? Caser::snake($name)] = array_filter($fieldMapping);
167
                $objFields[$name] = $annotation->getName() ?? Caser::snake($name);
168
                $arrayFields[$annotation->getName() ?? Caser::snake($name)] = $name;
169
            }
170
        }
171
172
        //Embeded fields are option compared to the array or object mapping.
173
        if ($embeddedFields) {
174
            $cacheItem = $this->cache->fetch(self::EMBEDDED_CACHED_FIELDS) ?? [];
175
            $cacheItem[$class->getName()] = $embeddedFields;
176
            $t = $this->cache->save(self::EMBEDDED_CACHED_FIELDS, $cacheItem);
0 ignored issues
show
Unused Code introduced by
$t is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
177
        }
178
179
        $cacheItem = $this->cache->fetch(self::ARRAY_CACHED_FIELDS) ?? [];
180
        $cacheItem[$class->getName()] = $arrayFields;
181
        $this->cache->save(self::ARRAY_CACHED_FIELDS, $cacheItem);
182
183
        $cacheItem = $this->cache->fetch(self::OBJ_CACHED_FIELDS) ?? [];
184
        $cacheItem[$class->getName()] = $objFields;
185
        $this->cache->save(self::OBJ_CACHED_FIELDS, $cacheItem);
186
187
        return $mapping;
188
    }
189
190
    public function getPropertyMetadata(\ReflectionClass $class, bool $subClass = false): array
191
    {
192
        if ($class->isTrait() || (!$this->reader->getClassAnnotation($class, Index::class) && !$subClass)) {
193
            return [];
194
        }
195
196
        $metadata = [];
197
198
        /** @var \ReflectionProperty $property */
199
        foreach ($this->getDocumentPropertiesReflection($class) as $name => $property) {
200
            /** @var AbstractAnnotation $annotation */
201
            foreach ($this->reader->getPropertyAnnotations($property) as $annotation) {
202
                if (!$annotation instanceof PropertiesAwareInterface) {
203
                    continue;
204
                }
205
206
                $propertyMetadata = [
207
                    'identifier' => false,
208
                    'class' => null,
209
                    'embeded' => false,
210
                    'public' => $property->isPublic(),
211
                    'getter' => null,
212
                    'setter' => null,
213
                    'sub_properties' => []
214
                ];
215
216
                $name = $property->getName();
217
                $propertyMetadata['name'] = $name;
218
219
                if (!$propertyMetadata['public']) {
220
                    $propertyMetadata['getter'] = $this->guessGetter($class, $name);
221
                }
222
223
                $fieldMapping = $annotation->getSettings();
0 ignored issues
show
Unused Code introduced by
$fieldMapping is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
224
225
                if ($annotation instanceof Id) {
226
                    $propertyMetadata['identifier'] = true;
227
                    $propertyMetadata['setter'] = null;
228
                } else {
229
                    if (!$propertyMetadata['public']) {
230
                        $propertyMetadata['setter'] = $this->guessSetter($class, $name);
231
                    }
232
                }
233
234
                if ($annotation instanceof Embedded) {
235
                    $propertyMetadata['embeded'] = true;
236
                    $propertyMetadata['class'] = $annotation->class;
237
                    $propertyMetadata['sub_properties'] = $this->getPropertyMetadata(
238
                        new \ReflectionClass($annotation->class),
239
                        true
240
                    );
241
                }
242
243
                $metadata[$annotation->getName() ?? Caser::snake($name)] = $propertyMetadata;
244
            }
245
        }
246
247
        return $metadata;
248
    }
249
250
    public function getAnalysisConfig(\ReflectionClass $class): array
251
    {
252
        $config = [];
253
        $mapping = $this->getClassMetadata($class);
254
255
        //Think how to remove these array merge
256
        $analyzers = $this->getListFromArrayByKey('analyzer', $mapping);
257
        $analyzers = array_merge($analyzers, $this->getListFromArrayByKey('search_analyzer', $mapping));
258
        $analyzers = array_merge($analyzers, $this->getListFromArrayByKey('search_quote_analyzer', $mapping));
259
260
        foreach ($analyzers as $analyzer) {
261
            if (isset($this->analysisConfig['analyzer'][$analyzer])) {
262
                $config['analyzer'][$analyzer] = $this->analysisConfig['analyzer'][$analyzer];
263
            }
264
        }
265
266
        foreach (['tokenizer', 'filter', 'normalizer', 'char_filter'] as $type) {
267
            $list = $this->getListFromArrayByKey($type, $config);
268
269
            foreach ($list as $listItem) {
270
                if (isset($this->analysisConfig[$type][$listItem])) {
271
                    $config[$type][$listItem] = $this->analysisConfig[$type][$listItem];
272
                }
273
            }
274
        }
275
276
        return $config;
277
    }
278
279
    private function guessGetter(\ReflectionClass $class, $name): string
280
    {
281
        if ($class->hasMethod($name)) {
282
            return $name;
283
        }
284
285
        if ($class->hasMethod('get' . ucfirst($name))) {
286
            return 'get' . ucfirst($name);
287
        }
288
289
        if ($class->hasMethod('is' . ucfirst($name))) {
290
            return 'get' . ucfirst($name);
291
        }
292
293
        throw new \Exception("Could not determine a getter for `$name` of class `{$class->getNamespaceName()}`");
294
    }
295
296
    private function guessSetter(\ReflectionClass $class, $name): string
297
    {
298
        if ($class->hasMethod('set' . ucfirst($name))) {
299
            return 'set' . ucfirst($name);
300
        }
301
302
        throw new \Exception("Could not determine a setter for `$name` of class `{$class->getNamespaceName()}`");
303
    }
304
305
    private function getListFromArrayByKey(string $searchKey, array $array): array
306
    {
307
        $list = [];
308
309
        foreach (new \RecursiveIteratorIterator(
310
            new \RecursiveArrayIterator($array),
311
            \RecursiveIteratorIterator::SELF_FIRST
312
        ) as $key => $value) {
313
            if ($key === $searchKey) {
314
                if (is_array($value)) {
315
                    $list = array_merge($list, $value);
316
                } else {
317
                    $list[] = $value;
318
                }
319
            }
320
        }
321
322
        return array_unique($list);
323
    }
324
325
    private function getObjectMappingType(\ReflectionClass $class): string
326
    {
327
        switch (true) {
328
            case $this->reader->getClassAnnotation($class, ObjectType::class):
329
                $type = ObjectType::TYPE;
330
                break;
331
            case $this->reader->getClassAnnotation($class, NestedType::class):
332
                $type = NestedType::TYPE;
333
                break;
334
            default:
335
                throw new \LogicException(
336
                    sprintf(
337
                        '%s must be used @ObjectType or @NestedType as embeddable object.',
338
                        $class->getName()
339
                    )
340
                );
341
        }
342
343
        return $type;
344
    }
345
346
    private function getDocumentPropertiesReflection(\ReflectionClass $class): array
347
    {
348
        if (in_array($class->getName(), $this->properties)) {
349
            return $this->properties[$class->getName()];
350
        }
351
352
        $properties = [];
353
354
        foreach ($class->getProperties() as $property) {
355
            if (!in_array($property->getName(), $properties)) {
356
                $properties[$property->getName()] = $property;
357
            }
358
        }
359
360
        $parentReflection = $class->getParentClass();
361
        if ($parentReflection !== false) {
362
            $properties = array_merge(
363
                $properties,
364
                array_diff_key($this->getDocumentPropertiesReflection($parentReflection), $properties)
365
            );
366
        }
367
368
        $this->properties[$class->getName()] = $properties;
369
370
        return $properties;
371
    }
372
}
373