Passed
Push — hans/core-extraction ( 9ca3f7...ed2510 )
by Simon
05:43
created

FieldResolver   A

Complexity

Total Complexity 37

Size/Duplication

Total Lines 330
Duplicated Lines 0 %

Test Coverage

Coverage 98.15%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 96
dl 0
loc 330
ccs 106
cts 108
cp 0.9815
rs 9.44
c 3
b 0
f 0
wmc 37

12 Methods

Rating   Name   Duplication   Size   Complexity  
A isSubclassOf() 0 7 2
A getHierarchy() 0 21 5
A getHierarchyClasses() 0 9 1
A getRelationData() 0 14 4
A excludeDataObjectIDx() 0 9 2
A getSubClasses() 0 8 2
A getSourceName() 0 5 1
A getFoundOriginData() 0 22 2
A getFieldOptions() 0 24 5
A getType() 0 15 3
A resolveRelation() 0 22 5
A resolveField() 0 33 5
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 1
    public static function isSubclassOf($class, $instanceOf): bool
40
    {
41 1
        $ancestry = self::$ancestry[$class] ?? self::$ancestry[$class] = ClassInfo::ancestry($class);
42
43 1
        return is_array($instanceOf) ?
44 1
            (bool)array_intersect($instanceOf, $ancestry) :
45 1
            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 37
    public function resolveField($field)
57
    {
58 37
        $fullfield = str_replace('.', '_', $field);
59
60 37
        $sources = $this->index->getClasses();
61 37
        $buildSources = [];
62
63 37
        $schemaHelper = DataObject::getSchema();
64 37
        foreach ($sources as $source) {
65 37
            $buildSources[$source]['base'] = $schemaHelper->baseDataClass($source);
66
        }
67
68 37
        $found = [];
69
70 37
        if (strpos($field, '.') !== false) {
71 37
            $lookups = explode('.', $field);
72 37
            $field = array_pop($lookups);
73
74 37
            foreach ($lookups as $lookup) {
75 37
                $next = [];
76
77
                // @todo remove repetition
78 37
                foreach ($buildSources as $source => $baseOptions) {
79 37
                    $next = $this->resolveRelation($source, $lookup, $next);
80
                }
81
82 37
                $buildSources = $next;
83
            }
84
        }
85
86 37
        $found = $this->getFieldOptions($field, $buildSources, $fullfield, $found);
87
88 37
        return $found;
89
    }
90
91
    /**
92
     * Resolve relations if possible
93
     *
94
     * @param string $source
95
     * @param $lookup
96
     * @param array $next
97
     * @return array
98
     * @throws Exception
99
     */
100 37
    protected function resolveRelation($source, $lookup, array $next): array
101
    {
102 37
        $source = $this->getSourceName($source);
103
104 37
        foreach (self::getHierarchy($source) as $dataClass) {
105 37
            $schema = DataObject::getSchema();
106 37
            $options = ['multi_valued' => false];
107
108 37
            $class = $this->getRelationData($lookup, $schema, $dataClass, $options);
109
110 37
            if (is_string($class) && $class) {
111 37
                if (!isset($options['origin'])) {
112 37
                    $options['origin'] = $dataClass;
113
                }
114
115
                // we add suffix here to prevent the relation to be overwritten by other instances
116
                // all sources lookups must clean the source name before reading it via getSourceName()
117 37
                $next[$class . '|xkcd|' . $dataClass] = $options;
118
            }
119
        }
120
121 37
        return $next;
122
    }
123
124
    /**
125
     * This is used to clean the source name from suffix
126
     * suffixes are needed to support multiple relations with the same name on different page types
127
     *
128
     * @param string $source
129
     * @return string
130
     */
131 37
    private function getSourceName($source)
132
    {
133 37
        $explodedSource = explode('|xkcd|', $source);
134
135 37
        return $explodedSource[0];
136
    }
137
138
    /**
139
     * Get all the classes involved in a DataObject hierarchy - both super and optionally subclasses
140
     *
141
     * @static
142
     * @param string $class - The class to query
143
     * @param bool $includeSubclasses - True to return subclasses as well as super classes
144
     * @param bool $dataOnly - True to only return classes that have tables
145
     * @return array - Integer keys, String values as classes sorted by depth (most super first)
146
     * @throws ReflectionException
147
     */
148 79
    public static function getHierarchy($class, $includeSubclasses = true, $dataOnly = false): array
149
    {
150
        // Generate the unique key for this class and it's call type
151
        // It's a short-lived cache key for the duration of the request
152 79
        $cacheKey = sprintf('%s-%s-%s', $class, $includeSubclasses ? 'sc' : 'an', $dataOnly ? 'do' : 'al');
153
154 79
        if (!isset(self::$hierarchy[$cacheKey])) {
155 5
            $classes = self::getHierarchyClasses($class, $includeSubclasses);
156
157 5
            if ($dataOnly) {
158 1
                $classes = array_filter($classes, static function ($class) {
159 1
                    return DataObject::getSchema()->classHasTable($class);
160 1
                });
161
            }
162
163 5
            self::$hierarchy[$cacheKey] = array_values($classes);
164
165 5
            return array_values($classes);
166
        }
167
168 79
        return self::$hierarchy[$cacheKey];
169
    }
170
171
    /**
172
     * Get the hierarchy for a class
173
     *
174
     * @param $class
175
     * @param $includeSubclasses
176
     * @return array
177
     * @throws ReflectionException
178
     * @todo clean this up to be more compatible with PHP features
179
     */
180 5
    protected static function getHierarchyClasses($class, $includeSubclasses): array
181
    {
182 5
        $classes = array_values(ClassInfo::ancestry($class));
183 5
        $classes = self::getSubClasses($class, $includeSubclasses, $classes);
184
185 5
        $classes = array_unique($classes);
186 5
        $classes = self::excludeDataObjectIDx($classes);
187
188 5
        return $classes;
189
    }
190
191
    /**
192
     * Get the subclasses for the given class
193
     * Should be replaced with PHP native methods
194
     *
195
     * @param $class
196
     * @param $includeSubclasses
197
     * @param array $classes
198
     * @return array
199
     * @throws ReflectionException
200
     */
201 5
    private static function getSubClasses($class, $includeSubclasses, array $classes): array
202
    {
203 5
        if ($includeSubclasses) {
204 4
            $subClasses = ClassInfo::subclassesFor($class);
205 4
            $classes = array_merge($classes, array_values($subClasses));
206
        }
207
208 5
        return $classes;
209
    }
210
211
    /**
212
     * Objects to exclude from the index
213
     *
214
     * @param array $classes
215
     * @return array
216
     */
217 5
    private static function excludeDataObjectIDx(array $classes): array
218
    {
219
        // Remove all classes below DataObject from the list
220 5
        $idx = array_search(DataObject::class, $classes, true);
221 5
        if ($idx !== false) {
222 5
            array_splice($classes, 0, $idx + 1);
223
        }
224
225 5
        return $classes;
226
    }
227
228
    /**
229
     * Relational data
230
     *
231
     * @param $lookup
232
     * @param DataObjectSchema $schema
233
     * @param $className
234
     * @param array $options
235
     * @return string|array|null
236
     * @throws Exception
237
     */
238 37
    protected function getRelationData($lookup, DataObjectSchema $schema, $className, array &$options)
239
    {
240 37
        if ($hasOne = $schema->hasOneComponent($className, $lookup)) {
241 37
            return $hasOne;
242
        }
243 37
        $options['multi_valued'] = true;
244 37
        if ($hasMany = $schema->hasManyComponent($className, $lookup)) {
245 37
            return $hasMany;
246
        }
247 37
        if ($key = $schema->manyManyComponent($className, $lookup)) {
248
            return $key['childClass'];
249
        }
250
251 37
        return null;
252
    }
253
254
    /**
255
     * Create field options for the given index field
256
     *
257
     * @param $field
258
     * @param array $sources
259
     * @param string $fullfield
260
     * @param array $found
261
     * @return array
262
     * @throws ReflectionException
263
     */
264 37
    protected function getFieldOptions($field, array $sources, $fullfield, array $found): array
265
    {
266 37
        foreach ($sources as $class => $fieldOptions) {
267 37
            $class = $this->getSourceName($class);
268 36
            $dataclasses = self::getHierarchy($class);
269
270 37
            $fields = DataObject::getSchema()->databaseFields($class);
271 37
            while ($dataclass = array_shift($dataclasses)) {
272
                $type = $this->getType($fields, $field, $dataclass);
273 37
274 37
                if ($type) {
275 37
                    // Don't search through child classes of a class we matched on.
276
                    $dataclasses = array_diff($dataclasses, array_values(ClassInfo::subclassesFor($dataclass)));
277 37
                    // Trim arguments off the type string
278
                    if (preg_match('/^(\w+)\(/', $type, $match)) {
279 37
                        $type = $match[1];
280
                    }
281 37
282 37
                    $found = $this->getFoundOriginData($field, $fullfield, $fieldOptions, $dataclass, $type, $found);
283
                }
284
            }
285 37
        }
286
287
        return $found;
288 37
    }
289
290
    /**
291
     * Get the type of this field
292 37
     *
293
     * @param array $fields
294
     * @param string $field
295
     * @param string $dataclass
296
     * @return string
297
     */
298
    protected function getType($fields, $field, $dataclass): string
299
    {
300
        if (!empty($fields[$field])) {
301
            return $fields[$field];
302
        }
303 37
304
        $singleton = singleton($dataclass);
305 37
306 37
        $type = $singleton->castingClass($field);
307
        if (!$type) {
308
            // @todo should this be null?
309 17
            $type = 'String';
310
        }
311 17
312 17
        return $type;
313
    }
314
315
    /**
316
     * FoundOriginData is a helper to make sure the options are properly set.
317 17
     *
318
     * @param string $field
319
     * @param string $fullField
320
     * @param array $fieldOptions
321
     * @param string $dataclass
322
     * @param string $type
323
     * @param array $found
324
     * @return array
325
     */
326
    private function getFoundOriginData(
327
        $field,
328
        $fullField,
329
        $fieldOptions,
330
        $dataclass,
331 37
        $type,
332
        $found
333
    ): array {
334 37
        // Get the origin
335
        $origin = $fieldOptions['origin'] ?? $dataclass;
336 37
337 37
        $found["{$origin}_{$fullField}"] = [
338 37
            'name'         => "{$origin}_{$fullField}",
339 37
            'field'        => $field,
340 37
            'fullfield'    => $fullField,
341 37
            'origin'       => $origin,
342 37
            'class'        => $dataclass,
343 37
            'type'         => $type,
344
            'multi_valued' => isset($fieldOptions['multi_valued']) ? true : false,
345
        ];
346 37
347
        return $found;
348
    }
349
}
350