Passed
Push — hans/relation-fix ( 9a8dd6...0ede04 )
by Simon
09:18
created

FieldResolver   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 384
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 106
c 4
b 0
f 0
dl 0
loc 384
rs 8.96
wmc 43

15 Methods

Rating   Name   Duplication   Size   Complexity  
A isSubclassOf() 0 7 2
A getFoundOriginData() 0 22 2
A getFieldOptions() 0 24 5
A getBuildSources() 0 11 2
A getType() 0 17 3
A getHierarchy() 0 21 5
A getHierarchyClasses() 0 9 1
A resolveRelation() 0 22 5
A getRelationData() 0 14 4
A excludeDataObjectIDx() 0 9 2
A getNextOption() 0 13 4
A resolveField() 0 21 3
A getSubClasses() 0 8 2
A getSourceName() 0 5 1
A getNext() 0 12 2

How to fix   Complexity   

Complex Class

Complex classes like FieldResolver often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FieldResolver, and based on these observations, apply Extract Interface, too.

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