Passed
Push — master ( 15b2c5...7c78fb )
by Marco
06:02
created

FieldResolver::getSourceName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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