Completed
Pull Request — 6.1-dev (#893)
by Christoph
01:32
created

DocumentParser::guessGetter()   B

Complexity

Conditions 9
Paths 7

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 8.0555
c 0
b 0
f 0
cc 9
nc 7
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
            $parts = explode('_', $name);
295
            $name = '';
296
            foreach ($parts as $part) {
297
                if ($part) {
298
                    $name .= \ucfirst($part);
299
                }
300
            }
301
            if ($class->hasMethod('get' . $name)) {
302
                return 'get' . $name;
303
            }
304
            if ($class->hasMethod('is' . $name)) {
305
                return 'is' . $name;
306
            }
307
        }
308
309
        throw new \Exception("Could not determine a getter for `$name` of class `{$class->getNamespaceName()}`");
310
    }
311
312
    protected function guessSetter(\ReflectionClass $class, $name): string
313
    {
314
        if ($class->hasMethod('set' . ucfirst($name))) {
315
            return 'set' . ucfirst($name);
316
        }
317
318
        // if there are underscores in the name convert them to CamelCase
319
        if (strpos($name, '_')) {
320
            $parts = explode('_', $name);
321
            $name = '';
322
            foreach ($parts as $part) {
323
                if ($part) {
324
                    $name .= \ucfirst($part);
325
                }
326
            }
327
            if ($class->hasMethod('set' . $name)) {
328
                return 'set' . $name;
329
            }
330
        }
331
332
        throw new \Exception("Could not determine a setter for `$name` of class `{$class->getNamespaceName()}`");
333
    }
334
335
    private function getListFromArrayByKey(string $searchKey, array $array): array
336
    {
337
        $list = [];
338
339
        foreach (new \RecursiveIteratorIterator(
340
            new \RecursiveArrayIterator($array),
341
            \RecursiveIteratorIterator::SELF_FIRST
342
        ) as $key => $value) {
343
            if ($key === $searchKey) {
344
                if (is_array($value)) {
345
                    $list = array_merge($list, $value);
346
                } else {
347
                    $list[] = $value;
348
                }
349
            }
350
        }
351
352
        return array_unique($list);
353
    }
354
355
    private function getObjectMappingType(\ReflectionClass $class): string
356
    {
357
        switch (true) {
358
            case $this->reader->getClassAnnotation($class, ObjectType::class):
359
                $type = ObjectType::TYPE;
360
                break;
361
            case $this->reader->getClassAnnotation($class, NestedType::class):
362
                $type = NestedType::TYPE;
363
                break;
364
            default:
365
                throw new \LogicException(
366
                    sprintf(
367
                        '%s must be used @ObjectType or @NestedType as embeddable object.',
368
                        $class->getName()
369
                    )
370
                );
371
        }
372
373
        return $type;
374
    }
375
376
    private function getDocumentPropertiesReflection(\ReflectionClass $class): array
377
    {
378
        if (in_array($class->getName(), $this->properties)) {
379
            return $this->properties[$class->getName()];
380
        }
381
382
        $properties = [];
383
384
        foreach ($class->getProperties() as $property) {
385
            if (!in_array($property->getName(), $properties)) {
386
                $properties[$property->getName()] = $property;
387
            }
388
        }
389
390
        $parentReflection = $class->getParentClass();
391
        if ($parentReflection !== false) {
392
            $properties = array_merge(
393
                $properties,
394
                array_diff_key($this->getDocumentPropertiesReflection($parentReflection), $properties)
395
            );
396
        }
397
398
        $this->properties[$class->getName()] = $properties;
399
400
        return $properties;
401
    }
402
}
403