Completed
Push — 6.1-dev ( 9fbc6d...9e864f )
by
unknown
16s queued 11s
created

DocumentParser::getListFromArrayByKey()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

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