Passed
Push — bufferfix ( 8c6da4...848e8a )
by Simon
10:44
created

FieldResolver::handleRelationData()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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