Passed
Push — hans/core-extraction ( ed2510...fc7dca )
by Simon
10:29 queued 08:21
created

FieldResolver::getBuildSources()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

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