Passed
Push — hans/authentication ( f88d5d...b8d786 )
by Simon
05:24
created

FieldResolver::isSubclassOf()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

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