Passed
Push — hans/bufferadd ( dd4951...8221cf )
by Simon
08:32 queued 06:25
created

FieldResolver::getSourceName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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