Passed
Push — master ( bc16c5...fce4c6 )
by Simon
06:43
created

DocumentFactory::buildItems()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 34
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 4

Importance

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