Passed
Push — hans/state-improvements ( 58acba...11f472 )
by Simon
07:14
created

FieldResolver::getSubClasses()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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