Passed
Push — hans/bufferadd ( a9e093...b7a745 )
by Simon
09:23
created

FieldResolver::getNextOption()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 5
c 0
b 0
f 0
nc 3
nop 4
dl 0
loc 13
ccs 0
cts 0
cp 0
crap 20
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);
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
     * @return array
125
     * @throws Exception
126
     */
127 36
    protected function resolveRelation($source, $lookup, array $next): array
128
    {
129 36
        $source = $this->getSourceName($source);
130
131 36
        foreach (self::getHierarchy($source) as $dataClass) {
132 36
            $schema = DataObject::getSchema();
133 36
            $options = ['multi_valued' => false];
134
135 36
            $class = $this->getRelationData($lookup, $schema, $dataClass, $options);
136
137 36
            list($options, $next) = $this->getNextOption($next, $class, $options, $dataClass);
0 ignored issues
show
Bug introduced by
It seems like $class can also be of type array; however, parameter $class of Firesphere\SolrSearch\He...solver::getNextOption() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

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