Passed
Pull Request — master (#188)
by Simon
08:49 queued 06:27
created

FieldResolver::findOrigin()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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