FieldResolver::getFoundOriginData()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 2
eloc 10
c 2
b 1
f 0
nc 2
nop 6
dl 0
loc 23
rs 9.9332
1
<?php
2
/**
3
 * class FieldResolver|Firesphere\SolrSearch\Helpers\FieldResolver Identify fields or relations in a DataObject
4
 *
5
 * @package Firesphere\Search\Backend
6
 * @author Simon `Firesphere` Erkelens; Marco `Sheepy` Hermo
7
 * @copyright Copyright (c) 2018 - now() Firesphere & Sheepy
8
 */
9
10
namespace Firesphere\SearchBackend\Helpers;
11
12
use Exception;
13
use Firesphere\SearchBackend\Traits\IntrospectionTraits\GetSetSearchResolverTrait;
14
use ReflectionException;
15
use SilverStripe\Core\ClassInfo;
16
use SilverStripe\ORM\DataObject;
17
use SilverStripe\ORM\DataObjectSchema;
18
19
/**
20
 * Class FieldResolver
21
 * Some additional introspection tools that are used often by the fulltext search code
22
 *
23
 * @package Firesphere\Search\Backend
24
 */
25
class FieldResolver
26
{
27
    use GetSetSearchResolverTrait;
28
29
    /**
30
     * @var array Class Ancestry
31
     */
32
    protected static $ancestry = [];
33
    /**
34
     * @var array Class Hierarchy, could be replaced with Ancestry
35
     */
36
    protected static $hierarchy = [];
37
38
    /**
39
     * Check if class is subclass of (a) the class in $instanceOf, or (b) any of the classes in the array $instanceOf
40
     *
41
     * @param string $class Name of the class to test
42
     * @param array|string $instanceOf Class ancestry it should be in
43
     * @return bool
44
     * @static
45
     */
46
    public static function isSubclassOf($class, $instanceOf): bool
47
    {
48
        $ancestry = self::$ancestry[$class] ?? self::$ancestry[$class] = ClassInfo::ancestry($class);
49
50
        if (is_array($instanceOf)) {
51
            return (bool)array_intersect($instanceOf, $ancestry);
52
        }
53
54
        return array_key_exists($instanceOf, $ancestry);
55
    }
56
57
    /**
58
     * Resolve a field ancestry
59
     *
60
     * @param $field
61
     * @return array
62
     * @throws Exception
63
     *
64
     */
65
    public function resolveField($field)
66
    {
67
        $fullfield = str_replace('.', '_', $field);
68
69
        $buildSources = $this->getBuildSources();
70
71
        $found = [];
72
73
        if (strpos($field, '.') !== false) {
74
            $lookups = explode('.', $field);
75
            $field = array_pop($lookups);
76
77
            foreach ($lookups as $lookup) {
78
                $buildSources = $this->getNext($buildSources, $lookup);
79
            }
80
        }
81
82
        $found = $this->getFieldOptions($field, $buildSources, $fullfield, $found);
83
84
        return $found;
85
    }
86
87
    /**
88
     * Get the sources to build in to a Solr field
89
     *
90
     * @return array
91
     */
92
    protected function getBuildSources(): array
93
    {
94
        $sources = $this->index->getClasses();
95
        $buildSources = [];
96
97
        $schemaHelper = DataObject::getSchema();
98
        foreach ($sources as $source) {
99
            $buildSources[$source]['base'] = $schemaHelper->baseDataClass($source);
100
        }
101
102
        return $buildSources;
103
    }
104
105
    /**
106
     * Get the next lookup item from the buildSources
107
     *
108
     * @param array $buildSources
109
     * @param $lookup
110
     * @return array
111
     * @throws Exception
112
     */
113
    protected function getNext(array $buildSources, $lookup): array
114
    {
115
        $next = [];
116
117
        // @todo remove repetition
118
        foreach ($buildSources as $source => $baseOptions) {
119
            $next = $this->resolveRelation($source, $lookup, $next, $baseOptions);
120
        }
121
122
        $buildSources = $next;
123
124
        return $buildSources;
125
    }
126
127
    /**
128
     * Resolve relations if possible
129
     *
130
     * @param string $source
131
     * @param $lookup
132
     * @param array $next
133
     * @param array $options
134
     * @return array
135
     * @throws ReflectionException
136
     * @throws Exception
137
     */
138
    protected function resolveRelation($source, $lookup, array $next, array &$options): array
139
    {
140
        $source = $this->getSourceName($source);
141
142
        foreach (self::getHierarchy($source) as $dataClass) {
143
            [$options, $next] = $this->resolveNext($options, $lookup, $dataClass, $source, $next);
144
        }
145
146
        return $next;
147
    }
148
149
    /**
150
     * This is used to clean the source name from suffix
151
     * suffixes are needed to support multiple relations with the same name on different page types
152
     *
153
     * @param string $source
154
     * @return string
155
     */
156
    private function getSourceName($source)
157
    {
158
        $explodedSource = explode('|xkcd|', $source);
159
160
        return $explodedSource[0];
161
    }
162
163
    /**
164
     * Get all the classes involved in a DataObject hierarchy - both super and optionally subclasses
165
     *
166
     * @static
167
     * @param string $class - The class to query
168
     * @param bool $dataOnly - True to only return classes that have tables
169
     * @return array - Integer keys, String values as classes sorted by depth (most super first)
170
     * @throws ReflectionException
171
     */
172
    public static function getHierarchy($class, $dataOnly = false): array
173
    {
174
        // Generate the unique key for this class and it's call type
175
        // It's a short-lived cache key for the duration of the request
176
        $cacheKey = sprintf('%s-sc-%s', $class, $dataOnly ? 'do' : 'al');
177
178
        if (!isset(self::$hierarchy[$cacheKey])) {
179
            $classes = self::getHierarchyClasses($class);
180
181
            if ($dataOnly) {
182
                $classes = array_filter($classes, static function ($class) {
183
                    return DataObject::getSchema()->classHasTable($class);
184
                });
185
            }
186
187
            self::$hierarchy[$cacheKey] = array_values($classes);
188
189
            return array_values($classes);
190
        }
191
192
        return self::$hierarchy[$cacheKey];
193
    }
194
195
    /**
196
     * Get the hierarchy for a class
197
     *
198
     * @param $class
199
     * @return array
200
     * @throws ReflectionException
201
     * @todo clean this up to be more compatible with PHP features
202
     */
203
    protected static function getHierarchyClasses($class): array
204
    {
205
        if (!isset(self::$ancestry[$class])) {
206
            self::$ancestry[$class] = array_values(ClassInfo::ancestry($class));
207
        }
208
        $ancestry = self::$ancestry[$class];
209
210
        $classes = self::getSubClasses($class, $ancestry);
211
212
        $classes = array_unique($classes);
213
        $classes = self::excludeDataObjectIDx($classes);
214
215
        return $classes;
216
    }
217
218
    /**
219
     * Get the subclasses for the given class
220
     * Should be replaced with PHP native methods
221
     *
222
     * @param $class
223
     * @param array $classes
224
     * @return array
225
     * @throws ReflectionException
226
     */
227
    private static function getSubClasses($class, array $classes): array
228
    {
229
        $subClasses = ClassInfo::subclassesFor($class);
230
        $classes = array_merge($classes, array_values($subClasses));
231
232
        return $classes;
233
    }
234
235
    /**
236
     * Objects to exclude from the index
237
     *
238
     * @param array $classes
239
     * @return array
240
     */
241
    private static function excludeDataObjectIDx(array $classes): array
242
    {
243
        // Remove all classes below DataObject from the list
244
        $idx = array_search(DataObject::class, $classes, true);
245
        if ($idx !== false) {
246
            array_splice($classes, 0, $idx + 1);
247
        }
248
249
        return $classes;
250
    }
251
252
    /**
253
     * Resolve the next item in line to be indexed
254
     *
255
     * @param array $options
256
     * @param $lookup
257
     * @param $dataClass
258
     * @param string $source
259
     * @param array $next
260
     * @return array[]
261
     * @throws Exception
262
     */
263
    protected function resolveNext(array $options, $lookup, $dataClass, string $source, array $next): array
264
    {
265
        $schema = DataObject::getSchema();
266
        $options['multi_valued'] = false;
267
268
        $class = $this->getRelationData($lookup, $schema, $dataClass, $options);
269
270
        if (is_string($class) && $class) {
271
            if (!isset($options['origin'])) {
272
                $options['origin'] = $source;
273
            }
274
275
            // we add suffix here to prevent the relation to be overwritten by other instances
276
            // all sources lookups must clean the source name before reading it via getSourceName()
277
            $next[$class . '|xkcd|' . $dataClass] = $options;
278
        }
279
280
        return [$options, $next];
281
    }
282
283
    /**
284
     * Relational data
285
     *
286
     * @param $lookup
287
     * @param DataObjectSchema $schema
288
     * @param $className
289
     * @param array $options
290
     * @return string|array|null
291
     * @throws Exception
292
     */
293
    protected function getRelationData($lookup, DataObjectSchema $schema, $className, array &$options)
294
    {
295
        if ($hasOne = $schema->hasOneComponent($className, $lookup)) {
296
            return $hasOne;
297
        }
298
        $options['multi_valued'] = true;
299
        if ($hasMany = $schema->hasManyComponent($className, $lookup)) {
300
            return $hasMany;
301
        }
302
        if ($key = $schema->manyManyComponent($className, $lookup)) {
303
            return $key['childClass'];
304
        }
305
306
        return null;
307
    }
308
309
    /**
310
     * Create field options for the given index field
311
     *
312
     * @param $field
313
     * @param array $sources
314
     * @param string $fullfield
315
     * @param array $found
316
     * @return array
317
     * @throws ReflectionException
318
     */
319
    protected function getFieldOptions($field, array $sources, $fullfield, array $found): array
320
    {
321
        foreach ($sources as $class => $fieldOptions) {
322
            $found = $this->findOrigin($field, $fullfield, $found, $class, $fieldOptions);
323
        }
324
325
        return $found;
326
    }
327
328
    /**
329
     * Find the origin of a field
330
     *
331
     * @param $field
332
     * @param $fullfield
333
     * @param array $found
334
     * @param $class
335
     * @param $fieldOptions
336
     * @return array
337
     * @throws ReflectionException
338
     */
339
    protected function findOrigin($field, $fullfield, array $found, $class, $fieldOptions): array
340
    {
341
        $class = $this->getSourceName($class);
342
        $dataclasses = self::getHierarchy($class);
343
344
        $fields = DataObject::getSchema()->databaseFields($class);
345
        while ($dataclass = array_shift($dataclasses)) {
346
            $type = $this->getType($fields, $field, $dataclass);
347
348
            if ($type) {
349
                // Don't search through child classes of a class we matched on.
350
                $dataclasses = array_diff($dataclasses, array_values(ClassInfo::subclassesFor($dataclass)));
351
                $found = $this->getOriginForType($field, $fullfield, $found, $fieldOptions, $dataclass, $type);
352
            }
353
        }
354
355
        return $found;
356
    }
357
358
    /**
359
     * Get the type of this field
360
     *
361
     * @param array $fields
362
     * @param string $field
363
     * @param string $dataclass
364
     * @return string
365
     */
366
    protected function getType($fields, $field, $dataclass): string
367
    {
368
        if (!empty($fields[$field])) {
369
            return $fields[$field];
370
        }
371
372
        /** @var DataObject $singleton */
373
        $singleton = singleton($dataclass);
374
375
        $type = $singleton->castingClass($field);
376
377
        if (!$type) {
378
            $type = 'String';
379
        }
380
381
        return $type;
382
    }
383
384
    /**
385
     * Extraction to find the origin for a specific type field
386
     *
387
     * @param $field
388
     * @param $fullfield
389
     * @param array $found
390
     * @param $fieldOptions
391
     * @param $dataclass
392
     * @param string $type
393
     * @return array
394
     */
395
    protected function getOriginForType(
396
        $field,
397
        $fullfield,
398
        array $found,
399
        $fieldOptions,
400
        $dataclass,
401
        string $type
402
    ): array
403
    {
404
        // Trim arguments off the type string
405
        if (preg_match('/^(\w+)\(/', $type, $match)) {
406
            $type = $match[1];
407
        }
408
409
        $found = $this->getFoundOriginData($field, $fullfield, $fieldOptions, $dataclass, $type, $found);
410
411
        return $found;
412
    }
413
414
    /**
415
     * FoundOriginData is a helper to make sure the options are properly set.
416
     *
417
     * @param string $field
418
     * @param string $fullField
419
     * @param array $fieldOptions
420
     * @param string $dataclass
421
     * @param string $type
422
     * @param array $found
423
     * @return array
424
     */
425
    private function getFoundOriginData(
426
        $field,
427
        $fullField,
428
        $fieldOptions,
429
        $dataclass,
430
        $type,
431
        $found
432
    ): array
433
    {
434
        // Get the origin
435
        $origin = $fieldOptions['origin'] ?? $dataclass;
436
437
        $found["{$origin}_{$fullField}"] = [
438
            'name'         => "{$origin}_{$fullField}",
439
            'field'        => $field,
440
            'fullfield'    => $fullField,
441
            'origin'       => $origin,
442
            'class'        => $dataclass,
443
            'type'         => $type,
444
            'multi_valued' => isset($fieldOptions['multi_valued']) ? true : false,
445
        ];
446
447
        return $found;
448
    }
449
}
450