Passed
Pull Request — master (#225)
by Simon
21:24 queued 05:14
created

FieldResolver::resolveNext()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 3
nop 5
dl 0
loc 18
ccs 9
cts 9
cp 1
crap 4
rs 10
c 0
b 0
f 0
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
    /**
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 1
    public static function isSubclassOf($class, $instanceOf): bool
47
    {
48 1
        $ancestry = self::$ancestry[$class] ?? self::$ancestry[$class] = ClassInfo::ancestry($class);
49
50 1
        if (is_array($instanceOf)) {
51 1
            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 41
    public function resolveField($field)
66
    {
67 41
        $fullfield = str_replace('.', '_', $field);
68
69 41
        $buildSources = $this->getBuildSources();
70
71 41
        $found = [];
72
73 41
        if (strpos($field, '.') !== false) {
74 40
            $lookups = explode('.', $field);
75 40
            $field = array_pop($lookups);
76
77 40
            foreach ($lookups as $lookup) {
78 40
                $buildSources = $this->getNext($buildSources, $lookup);
79
            }
80
        }
81
82 41
        $found = $this->getFieldOptions($field, $buildSources, $fullfield, $found);
83
84 41
        return $found;
85
    }
86
87
    /**
88
     * Get the sources to build in to a Solr field
89
     *
90
     * @return array
91
     */
92 41
    protected function getBuildSources(): array
93
    {
94 41
        $sources = $this->index->getClasses();
95 41
        $buildSources = [];
96
97 41
        $schemaHelper = DataObject::getSchema();
98 41
        foreach ($sources as $source) {
99 41
            $buildSources[$source]['base'] = $schemaHelper->baseDataClass($source);
100
        }
101
102 41
        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 40
    protected function getNext(array $buildSources, $lookup): array
114
    {
115 40
        $next = [];
116
117
        // @todo remove repetition
118 40
        foreach ($buildSources as $source => $baseOptions) {
119 40
            $next = $this->resolveRelation($source, $lookup, $next, $baseOptions);
120
        }
121
122 40
        $buildSources = $next;
123
124 40
        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 40
    protected function resolveRelation($source, $lookup, array $next, array &$options): array
139
    {
140 40
        $source = $this->getSourceName($source);
141
142 40
        foreach (self::getHierarchy($source) as $dataClass) {
143 40
            list($options, $next) = $this->resolveNext($options, $lookup, $dataClass, $source, $next);
144
        }
145
146 40
        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 41
    private function getSourceName($source)
157
    {
158 41
        $explodedSource = explode('|xkcd|', $source);
159
160 41
        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 45
    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 45
        $cacheKey = sprintf('%s-sc-%s', $class, $dataOnly ? 'do' : 'al');
177
178 45
        if (!isset(self::$hierarchy[$cacheKey])) {
179 5
            $classes = self::getHierarchyClasses($class);
180
181 5
            if ($dataOnly) {
182 1
                $classes = array_filter($classes, static function ($class) {
183 1
                    return DataObject::getSchema()->classHasTable($class);
184 1
                });
185
            }
186
187 5
            self::$hierarchy[$cacheKey] = array_values($classes);
188
189 5
            return array_values($classes);
190
        }
191
192 45
        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 5
    protected static function getHierarchyClasses($class): array
204
    {
205 5
        if (!isset(self::$ancestry[$class])) {
206 4
            self::$ancestry[$class] = array_values(ClassInfo::ancestry($class));
207
        }
208 5
        $ancestry = self::$ancestry[$class];
209
210 5
        $classes = self::getSubClasses($class, $ancestry);
211
212 5
        $classes = array_unique($classes);
213 5
        $classes = self::excludeDataObjectIDx($classes);
214
215 5
        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 5
    private static function getSubClasses($class, array $classes): array
228
    {
229 5
        $subClasses = ClassInfo::subclassesFor($class);
230 5
        $classes = array_merge($classes, array_values($subClasses));
231
232 5
        return $classes;
233
    }
234
235
    /**
236
     * Objects to exclude from the index
237
     *
238
     * @param array $classes
239
     * @return array
240
     */
241 5
    private static function excludeDataObjectIDx(array $classes): array
242
    {
243
        // Remove all classes below DataObject from the list
244 5
        $idx = array_search(DataObject::class, $classes, true);
245 5
        if ($idx !== false) {
246 5
            array_splice($classes, 0, $idx + 1);
247
        }
248
249 5
        return $classes;
250
    }
251
252
    /**
253
     * Relational data
254
     *
255
     * @param $lookup
256
     * @param DataObjectSchema $schema
257
     * @param $className
258
     * @param array $options
259
     * @return string|array|null
260
     * @throws Exception
261
     */
262 40
    protected function getRelationData($lookup, DataObjectSchema $schema, $className, array &$options)
263
    {
264 40
        if ($hasOne = $schema->hasOneComponent($className, $lookup)) {
265 40
            return $hasOne;
266
        }
267 40
        $options['multi_valued'] = true;
268 40
        if ($hasMany = $schema->hasManyComponent($className, $lookup)) {
269 40
            return $hasMany;
270
        }
271 40
        if ($key = $schema->manyManyComponent($className, $lookup)) {
272 40
            return $key['childClass'];
273
        }
274
275 40
        return null;
276
    }
277
278
    /**
279
     * Create field options for the given index field
280
     *
281
     * @param $field
282
     * @param array $sources
283
     * @param string $fullfield
284
     * @param array $found
285
     * @return array
286
     * @throws ReflectionException
287
     */
288 41
    protected function getFieldOptions($field, array $sources, $fullfield, array $found): array
289
    {
290 41
        foreach ($sources as $class => $fieldOptions) {
291 41
            $found = $this->findOrigin($field, $fullfield, $found, $class, $fieldOptions);
292
        }
293
294 41
        return $found;
295
    }
296
297
    /**
298
     * Find the origin of a field
299
     *
300
     * @param $field
301
     * @param $fullfield
302
     * @param array $found
303
     * @param $class
304
     * @param $fieldOptions
305
     * @return array
306
     * @throws ReflectionException
307
     */
308 41
    protected function findOrigin($field, $fullfield, array $found, $class, $fieldOptions): array
309
    {
310 41
        $class = $this->getSourceName($class);
311 41
        $dataclasses = self::getHierarchy($class);
312
313 41
        $fields = DataObject::getSchema()->databaseFields($class);
314 41
        while ($dataclass = array_shift($dataclasses)) {
315 41
            $type = $this->getType($fields, $field, $dataclass);
316
317 41
            if ($type) {
318
                // Don't search through child classes of a class we matched on.
319 41
                $dataclasses = array_diff($dataclasses, array_values(ClassInfo::subclassesFor($dataclass)));
320 41
                $found = $this->getOriginForType($field, $fullfield, $found, $fieldOptions, $dataclass, $type);
321
            }
322
        }
323
324 41
        return $found;
325
    }
326
327
    /**
328
     * Get the type of this field
329
     *
330
     * @param array $fields
331
     * @param string $field
332
     * @param string $dataclass
333
     * @return string
334
     */
335 41
    protected function getType($fields, $field, $dataclass): string
336
    {
337 41
        if (!empty($fields[$field])) {
338 41
            return $fields[$field];
339
        }
340
341
        /** @var DataObject $singleton */
342 39
        $singleton = singleton($dataclass);
343
344 39
        $type = $singleton->castingClass($field);
345
346 39
        if (!$type) {
347
            $type = 'String';
348
        }
349
350 39
        return $type;
351
    }
352
353
    /**
354
     * Extraction to find the origin for a specific type field
355
     *
356
     * @param $field
357
     * @param $fullfield
358
     * @param array $found
359
     * @param $fieldOptions
360
     * @param $dataclass
361
     * @param string $type
362
     * @return array
363
     */
364 41
    protected function getOriginForType(
365
        $field,
366
        $fullfield,
367
        array $found,
368
        $fieldOptions,
369
        $dataclass,
370
        string $type
371
    ): array {
372
        // Trim arguments off the type string
373 41
        if (preg_match('/^(\w+)\(/', $type, $match)) {
374 41
            $type = $match[1];
375
        }
376
377 41
        $found = $this->getFoundOriginData($field, $fullfield, $fieldOptions, $dataclass, $type, $found);
378
379 41
        return $found;
380
    }
381
382
    /**
383
     * FoundOriginData is a helper to make sure the options are properly set.
384
     *
385
     * @param string $field
386
     * @param string $fullField
387
     * @param array $fieldOptions
388
     * @param string $dataclass
389
     * @param string $type
390
     * @param array $found
391
     * @return array
392
     */
393 41
    private function getFoundOriginData(
394
        $field,
395
        $fullField,
396
        $fieldOptions,
397
        $dataclass,
398
        $type,
399
        $found
400
    ): array {
401
        // Get the origin
402 41
        $origin = $fieldOptions['origin'] ?? $dataclass;
403
404 41
        $found["{$origin}_{$fullField}"] = [
405 41
            'name'         => "{$origin}_{$fullField}",
406 41
            'field'        => $field,
407 41
            'fullfield'    => $fullField,
408 41
            'origin'       => $origin,
409 41
            'class'        => $dataclass,
410 41
            'type'         => $type,
411 41
            'multi_valued' => isset($fieldOptions['multi_valued']) ? true : false,
412
        ];
413
414 41
        return $found;
415
    }
416
417
    /**
418
     * @param array $options
419
     * @param $lookup
420
     * @param $dataClass
421
     * @param string $source
422
     * @param array $next
423
     * @return array[]
424
     * @throws Exception
425
     */
426 40
    protected function resolveNext(array $options, $lookup, $dataClass, string $source, array $next): array
427
    {
428 40
        $schema = DataObject::getSchema();
429 40
        $options['multi_valued'] = false;
430
431 40
        $class = $this->getRelationData($lookup, $schema, $dataClass, $options);
432
433 40
        if (is_string($class) && $class) {
434 40
            if (!isset($options['origin'])) {
435 40
                $options['origin'] = $source;
436
            }
437
438
            // we add suffix here to prevent the relation to be overwritten by other instances
439
            // all sources lookups must clean the source name before reading it via getSourceName()
440 40
            $next[$class . '|xkcd|' . $dataClass] = $options;
441
        }
442
443 40
        return [$options, $next];
444
    }
445
}
446