Passed
Push — hans/relation-fix ( b496d0...78c30c )
by Simon
08:24 queued 06:08
created

FieldResolver::handleRelationData()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 5
c 1
b 0
f 0
nc 3
nop 5
dl 0
loc 12
ccs 6
cts 6
cp 1
crap 4
rs 10
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 36
    public function resolveField($field)
57
    {
58 36
        $fullfield = str_replace('.', '_', $field);
59
60 36
        $buildSources = $this->getBuildSources();
61
62 36
        $found = [];
63
64 36
        if (strpos($field, '.') !== false) {
65 36
            $lookups = explode('.', $field);
66 36
            $field = array_pop($lookups);
67
68 36
            foreach ($lookups as $lookup) {
69 36
                $buildSources = $this->getNext($buildSources, $lookup);
70
            }
71
        }
72
73 36
        $found = $this->getFieldOptions($field, $buildSources, $fullfield, $found);
74
75 36
        return $found;
76
    }
77
78
    /**
79
     * Get the sources to build in to a Solr field
80
     *
81
     * @return array
82
     */
83 36
    protected function getBuildSources(): array
84
    {
85 36
        $sources = $this->index->getClasses();
86 36
        $buildSources = [];
87
88 36
        $schemaHelper = DataObject::getSchema();
89 36
        foreach ($sources as $source) {
90 36
            $buildSources[$source]['base'] = $schemaHelper->baseDataClass($source);
91
        }
92
93 36
        return $buildSources;
94
    }
95
96
    /**
97
     * Get the next lookup item from the buildSources
98
     *
99
     * @param array $buildSources
100
     * @param $lookup
101
     * @return array
102
     * @throws Exception
103
     */
104 36
    protected function getNext(array $buildSources, $lookup): array
105
    {
106 36
        $next = [];
107
108
        // @todo remove repetition
109 36
        foreach ($buildSources as $source => $baseOptions) {
110 36
            $next = $this->resolveRelation($source, $lookup, $next, $baseOptions);
111
        }
112
113 36
        $buildSources = $next;
114
115 36
        return $buildSources;
116
    }
117
118
    /**
119
     * Resolve relations if possible
120
     *
121
     * @param string $source
122
     * @param $lookup
123
     * @param array $next
124
     * @param array $options
125
     * @return array
126
     * @throws ReflectionException
127
     * @throws Exception
128
     */
129 36
    protected function resolveRelation($source, $lookup, array $next, array &$options): array
130
    {
131 36
        $source = $this->getSourceName($source);
132
133 36
        foreach (self::getHierarchy($source) as $dataClass) {
134 36
            $schema = DataObject::getSchema();
135 36
            $options['multi_valued'] = false;
136
137 36
            $class = $this->getRelationData($lookup, $schema, $dataClass, $options);
138
139 36
            list($options, $next) = $this->handleRelationData($source, $next, $options, $class, $dataClass);
0 ignored issues
show
Bug introduced by
$source of type string is incompatible with the type array expected by parameter $source of Firesphere\SolrSearch\He...r::handleRelationData(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

139
            list($options, $next) = $this->handleRelationData(/** @scrutinizer ignore-type */ $source, $next, $options, $class, $dataClass);
Loading history...
140
        }
141
142 36
        return $next;
143
    }
144
145
    /**
146
     * This is used to clean the source name from suffix
147
     * suffixes are needed to support multiple relations with the same name on different page types
148
     *
149
     * @param string $source
150
     * @return string
151
     */
152 36
    private function getSourceName($source)
153
    {
154 36
        $explodedSource = explode('|xkcd|', $source);
155
156 36
        return $explodedSource[0];
157
    }
158
159
    /**
160
     * Get all the classes involved in a DataObject hierarchy - both super and optionally subclasses
161
     *
162
     * @static
163
     * @param string $class - The class to query
164
     * @param bool $includeSubclasses - True to return subclasses as well as super classes
165
     * @param bool $dataOnly - True to only return classes that have tables
166
     * @return array - Integer keys, String values as classes sorted by depth (most super first)
167
     * @throws ReflectionException
168
     */
169 78
    public static function getHierarchy($class, $includeSubclasses = true, $dataOnly = false): array
170
    {
171
        // Generate the unique key for this class and it's call type
172
        // It's a short-lived cache key for the duration of the request
173 78
        $cacheKey = sprintf('%s-%s-%s', $class, $includeSubclasses ? 'sc' : 'an', $dataOnly ? 'do' : 'al');
174
175 78
        if (!isset(self::$hierarchy[$cacheKey])) {
176 5
            $classes = self::getHierarchyClasses($class, $includeSubclasses);
177
178 5
            if ($dataOnly) {
179 1
                $classes = array_filter($classes, static function ($class) {
180 1
                    return DataObject::getSchema()->classHasTable($class);
181 1
                });
182
            }
183
184 5
            self::$hierarchy[$cacheKey] = array_values($classes);
185
186 5
            return array_values($classes);
187
        }
188
189 78
        return self::$hierarchy[$cacheKey];
190
    }
191
192
    /**
193
     * Get the hierarchy for a class
194
     *
195
     * @param $class
196
     * @param $includeSubclasses
197
     * @return array
198
     * @throws ReflectionException
199
     * @todo clean this up to be more compatible with PHP features
200
     */
201 5
    protected static function getHierarchyClasses($class, $includeSubclasses): array
202
    {
203 5
        $classes = array_values(ClassInfo::ancestry($class));
204 5
        $classes = self::getSubClasses($class, $includeSubclasses, $classes);
205
206 5
        $classes = array_unique($classes);
207 5
        $classes = self::excludeDataObjectIDx($classes);
208
209 5
        return $classes;
210
    }
211
212
    /**
213
     * Get the subclasses for the given class
214
     * Should be replaced with PHP native methods
215
     *
216
     * @param $class
217
     * @param $includeSubclasses
218
     * @param array $classes
219
     * @return array
220
     * @throws ReflectionException
221
     */
222 5
    private static function getSubClasses($class, $includeSubclasses, array $classes): array
223
    {
224 5
        if ($includeSubclasses) {
225 4
            $subClasses = ClassInfo::subclassesFor($class);
226 4
            $classes = array_merge($classes, array_values($subClasses));
227
        }
228
229 5
        return $classes;
230
    }
231
232
    /**
233
     * Objects to exclude from the index
234
     *
235
     * @param array $classes
236
     * @return array
237
     */
238 5
    private static function excludeDataObjectIDx(array $classes): array
239
    {
240
        // Remove all classes below DataObject from the list
241 5
        $idx = array_search(DataObject::class, $classes, true);
242 5
        if ($idx !== false) {
243 5
            array_splice($classes, 0, $idx + 1);
244
        }
245
246 5
        return $classes;
247
    }
248
249
    /**
250
     * Relational data
251
     *
252
     * @param $lookup
253
     * @param DataObjectSchema $schema
254
     * @param $className
255
     * @param array $options
256
     * @return string|array|null
257
     * @throws Exception
258
     */
259 36
    protected function getRelationData($lookup, DataObjectSchema $schema, $className, array &$options)
260
    {
261 36
        if ($hasOne = $schema->hasOneComponent($className, $lookup)) {
262 36
            return $hasOne;
263
        }
264 36
        $options['multi_valued'] = true;
265 36
        if ($hasMany = $schema->hasManyComponent($className, $lookup)) {
266 36
            return $hasMany;
267
        }
268 36
        if ($key = $schema->manyManyComponent($className, $lookup)) {
269
            return $key['childClass'];
270
        }
271
272 36
        return null;
273
    }
274
275
    /**
276
     * @param array $next
277
     * @param array|string $class
278
     * @param array $options
279
     * @param string $dataClass
280
     * @return array
281
     */
282
    protected function getNextOption(array $next, $class, array $options, $dataClass): array
283
    {
284
        if (is_string($class) && $class) {
285
            if (!isset($options['origin'])) {
286
                $options['origin'] = $dataClass;
287
            }
288
289
            // we add suffix here to prevent the relation to be overwritten by other instances
290
            // all sources lookups must clean the source name before reading it via getSourceName()
291
            $next[$class . '|xkcd|' . $dataClass] = $options;
292
        }
293
294
        return [$options, $next];
295
    }
296
297
    /**
298
     * Create field options for the given index field
299
     *
300
     * @param $field
301
     * @param array $sources
302
     * @param string $fullfield
303
     * @param array $found
304
     * @return array
305
     * @throws ReflectionException
306
     */
307 36
    protected function getFieldOptions($field, array $sources, $fullfield, array $found): array
308
    {
309 36
        foreach ($sources as $class => $fieldOptions) {
310 36
            $class = $this->getSourceName($class);
311 36
            $dataclasses = self::getHierarchy($class);
312
313 36
            $fields = DataObject::getSchema()->databaseFields($class);
314 36
            while ($dataclass = array_shift($dataclasses)) {
315 36
                $type = $this->getType($fields, $field, $dataclass);
316
317 36
                if ($type) {
318
                    // Don't search through child classes of a class we matched on.
319 36
                    $dataclasses = array_diff($dataclasses, array_values(ClassInfo::subclassesFor($dataclass)));
320
                    // Trim arguments off the type string
321 36
                    if (preg_match('/^(\w+)\(/', $type, $match)) {
322 36
                        $type = $match[1];
323
                    }
324
325 36
                    $found = $this->getFoundOriginData($field, $fullfield, $fieldOptions, $dataclass, $type, $found);
326
                }
327
            }
328
        }
329
330 36
        return $found;
331
    }
332
333
    /**
334
     * Get the type of this field
335
     *
336
     * @param array $fields
337
     * @param string $field
338
     * @param string $dataclass
339
     * @return string
340
     */
341 36
    protected function getType($fields, $field, $dataclass): string
342
    {
343 36
        if (!empty($fields[$field])) {
344 36
            return $fields[$field];
345
        }
346
347
        /** @var DataObject $singleton */
348 35
        $singleton = singleton($dataclass);
349
350 35
        $type = $singleton->castingClass($field);
351
352 35
        if (!$type) {
353
            // @todo should this be null?
354
            $type = 'String';
355
        }
356
357 35
        return $type;
358
    }
359
360
    /**
361
     * FoundOriginData is a helper to make sure the options are properly set.
362
     *
363
     * @param string $field
364
     * @param string $fullField
365
     * @param array $fieldOptions
366
     * @param string $dataclass
367
     * @param string $type
368
     * @param array $found
369
     * @return array
370
     */
371 36
    private function getFoundOriginData(
372
        $field,
373
        $fullField,
374
        $fieldOptions,
375
        $dataclass,
376
        $type,
377
        $found
378
    ): array {
379
        // Get the origin
380 36
        $origin = $fieldOptions['origin'] ?? $dataclass;
381
382 36
        $found["{$origin}_{$fullField}"] = [
383 36
            'name'         => "{$origin}_{$fullField}",
384 36
            'field'        => $field,
385 36
            'fullfield'    => $fullField,
386 36
            'origin'       => $origin,
387 36
            'class'        => $dataclass,
388 36
            'type'         => $type,
389 36
            'multi_valued' => isset($fieldOptions['multi_valued']) ? true : false,
390
        ];
391
392 36
        return $found;
393
    }
394
395
    /**
396
     * Figure out the relational data for the given source etc.
397
     *
398
     * @param array $source
399
     * @param array $next
400
     * @param array $options
401
     * @param array|string|null $class
402
     * @param string|null $dataClass
403
     * @return array
404
     */
405 36
    protected function handleRelationData($source, array $next, array &$options, $class, $dataClass)
406
    {
407 36
        if (is_string($class) && $class) {
408 36
            if (!isset($options['origin'])) {
409 36
                $options['origin'] = $source;
410
            }
411
412
            // we add suffix here to prevent the relation to be overwritten by other instances
413
            // all sources lookups must clean the source name before reading it via getSourceName()
414 36
            $next[$class . '|xkcd|' . $dataClass] = $options;
415
        }
416 36
        return array($options, $next);
417
    }
418
}
419