Passed
Push — sheepy/elevation-configuration ( bdeab0...bcf7bc )
by Marco
18:34
created

FieldResolver::getHierarchyClasses()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 9
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
namespace Firesphere\SolrSearch\Helpers;
4
5
use Exception;
6
use Firesphere\SolrSearch\Traits\GetSetSearchIntrospectionTrait;
7
use ReflectionException;
8
use SilverStripe\Core\ClassInfo;
9
use SilverStripe\ORM\DataObject;
10
use SilverStripe\ORM\DataObjectSchema;
11
12
/**
13
 * @todo clean up unneeded methods
14
 * Some additional introspection tools that are used often by the fulltext search code
15
 */
16
class FieldResolver
17
{
18
    use GetSetSearchIntrospectionTrait;
19
    /**
20
     * @var array
21
     */
22
    protected static $ancestry = [];
23
    /**
24
     * @var array
25
     */
26
    protected static $hierarchy = [];
27
28
    /**
29
     * Check if class is subclass of (a) the class in $instanceOf, or (b) any of the classes in the array $instanceOf
30
     * @param string $class Name of the class to test
31
     * @param array|string $instanceOf Class ancestry it should be in
32
     * @return bool
33
     * @todo remove in favour of DataObjectSchema
34
     * @static
35
     */
36
    public static function isSubclassOf($class, $instanceOf): bool
37
    {
38
        $ancestry = self::$ancestry[$class] ?? self::$ancestry[$class] = ClassInfo::ancestry($class);
39
40
        return is_array($instanceOf) ?
41
            (bool)array_intersect($instanceOf, $ancestry) :
42
            array_key_exists($instanceOf, $ancestry);
43
    }
44
45
    /**
46
     * @param $field
47
     * @return array
48
     * @throws Exception
49
     *
50
     */
51
    public function resolveField($field)
52
    {
53
        $fullfield = str_replace('.', '_', $field);
54
        $sources = $this->index->getClasses();
55
        $buildSources = [];
56
57
        $schemaHelper = DataObject::getSchema();
58
        foreach ($sources as $source) {
59
            $buildSources[$source]['base'] = $schemaHelper->baseDataClass($source);
60
        }
61
62
        $found = [];
63
64
        if (strpos($field, '.') !== false) {
65
            $lookups = explode('.', $field);
66
            $field = array_pop($lookups);
67
68
            foreach ($lookups as $lookup) {
69
                $next = [];
70
71
                // @todo remove repetition
72
                foreach ($buildSources as $source => $baseOptions) {
73
                    $next = $this->resolveRelation($source, $lookup, $next);
74
                }
75
76
                $buildSources = $next;
77
            }
78
        }
79
80
        $found = $this->getFieldOptions($field, $buildSources, $fullfield, $found);
81
82
        return $found;
83
    }
84
85
    /**
86
     * @param $source
87
     * @param $lookup
88
     * @param array $next
89
     * @return array
90
     * @throws Exception
91
     */
92
    protected function resolveRelation($source, $lookup, array $next): array
93
    {
94
        $source = $this->getSourceName($source);
95
96
        foreach (self::getHierarchy($source) as $dataClass) {
97
            $schema = DataObject::getSchema();
98
            $options = ['multi_valued' => false];
99
100
            $class = $this->getRelationData($lookup, $schema, $dataClass, $options);
101
102
            if (is_string($class) && $class) {
103
                if (!isset($options['origin'])) {
104
                    $options['origin'] = $dataClass;
105
                }
106
107
                // we add suffix here to prevent the relation to be overwritten by other instances
108
                // all sources lookups must clean the source name before reading it via getSourceName()
109
                $next[$class . '|xkcd|' . $dataClass] = $options;
110
            }
111
        }
112
113
        return $next;
114
    }
115
116
    /**
117
     * This is used to clean the source name from suffix
118
     * suffixes are needed to support multiple relations with the same name on different page types
119
     * @param string $source
120
     * @return string
121
     */
122
    private function getSourceName($source)
123
    {
124
        $explodedSource = explode('|xkcd|', $source);
125
126
        return $explodedSource[0];
127
    }
128
129
    /**
130
     * Get all the classes involved in a DataObject hierarchy - both super and optionally subclasses
131
     *
132
     * @static
133
     * @param string $class - The class to query
134
     * @param bool $includeSubclasses - True to return subclasses as well as super classes
135
     * @param bool $dataOnly - True to only return classes that have tables
136
     * @return array - Integer keys, String values as classes sorted by depth (most super first)
137
     * @throws ReflectionException
138
     */
139
    public static function getHierarchy($class, $includeSubclasses = true, $dataOnly = false): array
140
    {
141
        // Generate the unique key for this class and it's call type
142
        // It's a short-lived cache key for the duration of the request
143
        $cacheKey = sprintf('%s-%s-%s', $class, $includeSubclasses ? 'sc' : 'an', $dataOnly ? 'do' : 'al');
144
145
        if (!isset(self::$hierarchy[$cacheKey])) {
146
            $classes = self::getHierarchyClasses($class, $includeSubclasses);
147
148
            if ($dataOnly) {
149
                $classes = array_filter($classes, static function ($class) {
150
                    return DataObject::getSchema()->classHasTable($class);
151
                });
152
            }
153
154
            self::$hierarchy[$cacheKey] = array_values($classes);
155
156
            return array_values($classes);
157
        }
158
159
        return self::$hierarchy[$cacheKey];
160
    }
161
162
    /**
163
     * @param $class
164
     * @param $includeSubclasses
165
     * @return array
166
     * @throws ReflectionException
167
     */
168
    protected static function getHierarchyClasses($class, $includeSubclasses): array
169
    {
170
        $classes = array_values(ClassInfo::ancestry($class));
171
        $classes = self::getSubClasses($class, $includeSubclasses, $classes);
172
173
        $classes = array_unique($classes);
174
        $classes = self::excludeDataObjectIDx($classes);
175
176
        return $classes;
177
    }
178
179
    /**
180
     * @param $class
181
     * @param $includeSubclasses
182
     * @param array $classes
183
     * @return array
184
     * @throws ReflectionException
185
     */
186
    private static function getSubClasses($class, $includeSubclasses, array $classes): array
187
    {
188
        if ($includeSubclasses) {
189
            $subClasses = ClassInfo::subclassesFor($class);
190
            $classes = array_merge($classes, array_values($subClasses));
191
        }
192
193
        return $classes;
194
    }
195
196
    /**
197
     * @param array $classes
198
     * @return array
199
     */
200
    private static function excludeDataObjectIDx(array $classes): array
201
    {
202
        // Remove all classes below DataObject from the list
203
        $idx = array_search(DataObject::class, $classes, true);
204
        if ($idx !== false) {
205
            array_splice($classes, 0, $idx + 1);
206
        }
207
208
        return $classes;
209
    }
210
211
    /**
212
     * @param $lookup
213
     * @param DataObjectSchema $schema
214
     * @param $className
215
     * @param array $options
216
     * @return string|array|null
217
     * @throws Exception
218
     */
219
    protected function getRelationData($lookup, DataObjectSchema $schema, $className, array &$options)
220
    {
221
        if ($hasOne = $schema->hasOneComponent($className, $lookup)) {
222
            return $hasOne;
223
        }
224
        if ($hasMany = $schema->hasManyComponent($className, $lookup)) {
225
            $options['multi_valued'] = true;
226
227
            return $hasMany;
228
        }
229
        if ($key = $schema->manyManyComponent($className, $lookup)) {
230
            $options['multi_valued'] = true;
231
232
            return $key['childClass'];
233
        }
234
235
        return null;
236
    }
237
238
    /**
239
     * @param $field
240
     * @param array $sources
241
     * @param $fullfield
242
     * @param array $found
243
     * @return array
244
     * @throws ReflectionException
245
     */
246
    protected function getFieldOptions($field, array $sources, $fullfield, array $found): array
247
    {
248
        foreach ($sources as $class => $fieldOptions) {
249
            if (!empty($this->found[$class . '_' . $fullfield])) {
250
                return $this->found[$class . '_' . $fullfield];
251
            }
252
            $class = $this->getSourceName($class);
253
            $dataclasses = self::getHierarchy($class);
254
255
            $fields = DataObject::getSchema()->databaseFields($class);
256
            while ($dataclass = array_shift($dataclasses)) {
257
                $type = $this->getType($fields, $field, $dataclass);
258
259
                if ($type) {
260
                    // Don't search through child classes of a class we matched on. TODO: Should we?
261
                    $dataclasses = array_diff($dataclasses, array_values(ClassInfo::subclassesFor($dataclass)));
262
                    // Trim arguments off the type string
263
                    if (preg_match('/^(\w+)\(/', $type, $match)) {
264
                        $type = $match[1];
265
                    }
266
267
                    $found = $this->getFoundOriginData($field, $fullfield, $fieldOptions, $dataclass, $type, $found);
268
                }
269
            }
270
            $this->found[$class . '_' . $fullfield] = $found;
271
        }
272
273
274
        return $found;
275
    }
276
277
    /**
278
     * @param array $fields
279
     * @param string $field
280
     * @param string $dataclass
281
     * @return string
282
     */
283
    protected function getType($fields, $field, $dataclass)
284
    {
285
        if (!empty($fields[$field])) {
286
            return $fields[$field];
287
        }
288
289
        $singleton = singleton($dataclass);
290
        $type = $singleton->castingClass($field);
291
        if (!$type) {
292
            // @todo should this be null?
293
            $type = 'String';
294
        }
295
296
        return $type;
297
    }
298
299
    /**
300
     * @param string $field
301
     * @param string $fullfield
302
     * @param array $fieldOptions
303
     * @param string $dataclass
304
     * @param string $type
305
     * @param array $found
306
     * @return array
307
     */
308
    private function getFoundOriginData($field, $fullfield, $fieldOptions, $dataclass, $type, $found): array
309
    {
310
        // Get the origin
311
        $origin = $fieldOptions['origin'] ?? $dataclass;
312
313
        $found["{$origin}_{$fullfield}"] = [
314
            'name'         => "{$origin}_{$fullfield}",
315
            'field'        => $field,
316
            'fullfield'    => $fullfield,
317
            'origin'       => $origin,
318
            'class'        => $dataclass,
319
            'type'         => $type,
320
            'multi_valued' => isset($fieldOptions['multi_valued']) ? true : false,
321
        ];
322
323
        return $found;
324
    }
325
}
326