Passed
Push — hans/code-cleanup ( 7f6349...96a9e1 )
by Simon
06:38
created

DocumentFactory   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 235
Duplicated Lines 0 %

Test Coverage

Coverage 97.37%

Importance

Changes 23
Bugs 3 Features 0
Metric Value
eloc 71
c 23
b 3
f 0
dl 0
loc 235
ccs 74
cts 76
cp 0.9737
rs 10
wmc 26

11 Methods

Rating   Name   Duplication   Size   Complexity  
A classEquals() 0 3 2
A __construct() 0 3 1
A addToDoc() 0 10 3
A buildFields() 0 7 3
A setDebug() 0 5 1
A addDefaultFields() 0 7 1
A getValuesForField() 0 9 2
A isDebug() 0 3 1
A classIs() 0 11 4
A addField() 0 19 4
A buildItems() 0 34 4
1
<?php
2
3
4
namespace Firesphere\SolrSearch\Factories;
5
6
use Exception;
7
use Firesphere\SolrSearch\Extensions\DataObjectExtension;
8
use Firesphere\SolrSearch\Helpers\DataResolver;
9
use Firesphere\SolrSearch\Helpers\FieldResolver;
10
use Firesphere\SolrSearch\Helpers\Statics;
11
use Firesphere\SolrSearch\Indexes\BaseIndex;
12
use Firesphere\SolrSearch\Services\SolrCoreService;
13
use Firesphere\SolrSearch\Traits\DocumentFactoryTrait;
14
use Firesphere\SolrSearch\Traits\LoggerTrait;
15
use SilverStripe\Core\ClassInfo;
16
use SilverStripe\Core\Config\Configurable;
17
use SilverStripe\Core\Extensible;
18
use SilverStripe\Core\Injector\Injector;
19
use SilverStripe\ORM\DataObject;
20
use SilverStripe\ORM\FieldType\DBDate;
21
use SilverStripe\ORM\FieldType\DBField;
22
use Solarium\QueryType\Update\Query\Document;
23
use Solarium\QueryType\Update\Query\Query;
24
25
/**
26
 * Class DocumentFactory
27
 * Factory to create documents to be pushed to Solr
28
 *
29
 * @package Firesphere\SolrSearch\Factories
30
 */
31
class DocumentFactory
32
{
33
    use Configurable;
34
    use Extensible;
35
    use DocumentFactoryTrait;
36
    use LoggerTrait;
37
38
    /**
39
     * Numeral types in Solr
40
     *
41
     * @var array
42
     */
43
    protected static $numerals = [
44
        'tint',
45
        'tfloat',
46
        'tdouble',
47
    ];
48
    /**
49
     * Debug this build
50
     *
51
     * @var bool
52
     */
53
    protected $debug = false;
54
55
    /**
56
     * DocumentFactory constructor, sets up the field resolver
57
     */
58 9
    public function __construct()
59
    {
60 9
        $this->fieldResolver = Injector::inst()->get(FieldResolver::class);
61 9
    }
62
63
    /**
64
     * Note, it can only take one type of class at a time!
65
     * So make sure you properly loop and set $class
66
     *
67
     * @param array $fields
68
     * @param BaseIndex $index
69
     * @param Query $update
70
     * @return array
71
     * @throws Exception
72
     */
73 6
    public function buildItems($fields, $index, $update): array
74
    {
75 6
        $class = $this->getClass();
76 6
        $this->getFieldResolver()->setIndex($index);
77 6
        $boostFields = $index->getBoostedFields();
78 6
        $docs = [];
79 6
        foreach ($this->getItems() as $item) {
80
            // Don't index items that should not show in search explicitly.
81
            // Just a "not" is insufficient, as it could be null or false (both meaning, not set)
82 6
            if ($item->ShowInSearch === 0) {
83 1
                continue;
84
            }
85
            /** @var Document $doc */
86 6
            $doc = $update->createDocument();
87 6
            $this->addDefaultFields($doc, $item);
88
89 6
            $this->buildFields($fields, $doc, $item, $boostFields);
90 6
            $item->destroy();
91
92 6
            $docs[] = $doc;
93
        }
94
95 6
        if ($this->debug) {
96 1
            $debugString = sprintf(
97 1
                'Indexing %s on %s (%s items)%s',
98 1
                $class,
99 1
                $index->getIndexName(),
100 1
                $this->getItems()->count(),
101 1
                PHP_EOL
102
            );
103 1
            $this->getLogger()->info($debugString);
104
        }
105
106 6
        return $docs;
107
    }
108
109
    /**
110
     * Add fields that should always be included
111
     *
112
     * @param Document $doc
113
     * @param DataObject|DataObjectExtension $item
114
     */
115 6
    protected function addDefaultFields(Document $doc, DataObject $item)
116
    {
117 6
        $doc->setKey(SolrCoreService::ID_FIELD, $item->ClassName . '-' . $item->ID);
118 6
        $doc->addField(SolrCoreService::CLASS_ID_FIELD, $item->ID);
119 6
        $doc->addField('ClassName', $item->ClassName);
120 6
        $doc->addField('ClassHierarchy', ClassInfo::ancestry($item));
121 6
        $doc->addField('ViewStatus', $item->getViewStatus());
122 6
    }
123
124
    /**
125
     * Create the required record for a field
126
     *
127
     * @param $fields
128
     * @param Document $doc
129
     * @param DataObject $item
130
     * @param array $boostFields
131
     * @throws Exception
132
     */
133 6
    protected function buildFields($fields, Document $doc, DataObject $item, array $boostFields): void
134
    {
135 6
        foreach ($fields as $field) {
136 6
            $fieldData = $this->getFieldResolver()->resolveField($field);
137 6
            foreach ($fieldData as $dataField => $options) {
138 6
                $options['boost'] = $boostFields[$field] ?? null;
139 6
                $this->addField($doc, $item, $options);
140
            }
141
        }
142 6
    }
143
144
    /**
145
     * Add a single field to the Solr index
146
     *
147
     * @param Document $doc
148
     * @param DataObject $object
149
     * @param array $options
150
     */
151 6
    protected function addField($doc, $object, $options): void
152
    {
153 6
        if (!$this->classIs($object, $options['origin'])) {
154
            return;
155
        }
156
157 6
        $this->extend('onBeforeAddField', $options);
158
159 6
        $valuesForField = $this->getValuesForField($object, $options);
160
161 6
        $typeMap = Statics::getTypeMap();
162 6
        $type = $typeMap[$options['type']] ?? $typeMap['*'];
163
164 6
        foreach ($valuesForField as $value) {
165 6
            if ($value === null) {
166 4
                continue;
167
            }
168 6
            $this->extend('onBeforeAddDoc', $options, $value);
169 6
            $this->addToDoc($doc, $options, $type, $value);
170
        }
171 6
    }
172
173
    /**
174
     * Determine if the given object is one of the given type
175
     *
176
     * @param string|DataObject $class
177
     * @param array|string $base Class or list of base classes
178
     * @return bool
179
     * @todo remove in favour of the inheritance check from PHP
180
     */
181 6
    protected function classIs($class, $base): bool
182
    {
183 6
        $base = is_array($base) ? $base : [$base];
184
185 6
        foreach ($base as $nextBase) {
186 6
            if ($this->classEquals($class, $nextBase)) {
187 6
                return true;
188
            }
189
        }
190
191
        return false;
192
    }
193
194
    /**
195
     * Check if a base class is an instance of the expected base group
196
     *
197
     * @param string|DataObject $class
198
     * @param string $base
199
     * @return bool
200
     */
201 6
    protected function classEquals($class, $base): bool
202
    {
203 6
        return $class === $base || ($class instanceof $base);
204
    }
205
206
    /**
207
     * Use the DataResolver to find the value(s) for a field.
208
     * Returns an array of values, and if it's multiple, it becomes a long array
209
     *
210
     * @param $object
211
     * @param $options
212
     * @return array
213
     */
214 6
    protected function getValuesForField($object, $options): array
215
    {
216
        try {
217 6
            $valuesForField = [DataResolver::identify($object, $options['fullfield'])];
218 5
        } catch (Exception $e) {
219 5
            $valuesForField = [];
220
        }
221
222 6
        return $valuesForField;
223
    }
224
225
    /**
226
     * Push field to a document
227
     *
228
     * @param Document $doc
229
     * @param array $options
230
     * @param string $type
231
     * @param DBField|string $value
232
     */
233 6
    protected function addToDoc($doc, $options, $type, $value): void
234
    {
235
        /* Solr requires dates in the form 1995-12-31T23:59:59Z, so we need to normalize to GMT */
236 6
        if ($type === 'tdate' || $value instanceof DBDate) {
237 5
            $value = gmdate('Y-m-d\TH:i:s\Z', strtotime($value));
238
        }
239
240 6
        $name = getShortFieldName($options['name']);
241
242 6
        $doc->addField($name, $value, $options['boost'], Document::MODIFIER_SET);
243 6
    }
244
245
    /**
246
     * Are we debugging?
247
     *
248
     * @return bool
249
     */
250 1
    public function isDebug(): bool
251
    {
252 1
        return $this->debug;
253
    }
254
255
    /**
256
     * Set to true if debugging should be enabled
257
     *
258
     * @param bool $debug
259
     * @return DocumentFactory
260
     */
261 7
    public function setDebug(bool $debug): DocumentFactory
262
    {
263 7
        $this->debug = $debug;
264
265 7
        return $this;
266
    }
267
}
268