AbstractIndexer::resolveFieldValue()   B
last analyzed

Complexity

Conditions 7
Paths 10

Size

Total Lines 72
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 9.5102

Importance

Changes 0
Metric Value
eloc 36
c 0
b 0
f 0
dl 0
loc 72
ccs 22
cts 35
cp 0.6286
rs 8.4106
cc 7
nc 10
nop 3
crap 9.5102

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace ApacheSolrForTypo3\Solr\IndexQueue;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2012-2015 Ingo Renner <[email protected]>
8
 *  All rights reserved
9
 *
10
 *  This script is part of the TYPO3 project. The TYPO3 project is
11
 *  free software; you can redistribute it and/or modify
12
 *  it under the terms of the GNU General Public License as published by
13
 *  the Free Software Foundation; either version 3 of the License, or
14
 *  (at your option) any later version.
15
 *
16
 *  The GNU General Public License can be found at
17
 *  http://www.gnu.org/copyleft/gpl.html.
18
 *
19
 *  This script is distributed in the hope that it will be useful,
20
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 *  GNU General Public License for more details.
23
 *
24
 *  This copyright notice MUST APPEAR in all copies of the script!
25
 ***************************************************************/
26
27
use ApacheSolrForTypo3\Solr\ContentObject\Classification;
28
use ApacheSolrForTypo3\Solr\ContentObject\Multivalue;
29
use ApacheSolrForTypo3\Solr\ContentObject\Relation;
30
use ApacheSolrForTypo3\Solr\System\Solr\Document\Document;
31
use TYPO3\CMS\Core\Core\Environment;
32
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
33
use TYPO3\CMS\Core\Utility\GeneralUtility;
34
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
35
36
/**
37
 * An abstract indexer class to collect a few common methods shared with other
38
 * indexers.
39
 *
40
 * @author Ingo Renner <[email protected]>
41
 */
42
abstract class AbstractIndexer
43
{
44
45
    /**
46
     * Holds the type of the data to be indexed, usually that is the table name.
47
     *
48
     * @var string
49
     */
50
    protected $type = '';
51
52
    /**
53
     * Holds field names that are denied to overwrite in thy indexing configuration.
54
     *
55
     * @var array
56
     */
57
    protected static $unAllowedOverrideFields = ['type'];
58
59
    /**
60
     * @param string $solrFieldName
61 66
     * @return bool
62
     */
63 66
    public static function isAllowedToOverrideField($solrFieldName)
64
    {
65
        return !in_array($solrFieldName, static::$unAllowedOverrideFields);
66
    }
67
68
    /**
69
     * Adds fields to the document as defined in $indexingConfiguration
70
     *
71
     * @param Document $document base document to add fields to
72
     * @param array $indexingConfiguration Indexing configuration / mapping
73
     * @param array $data Record data
74 19
     * @return Document Modified document with added fields
75
     */
76
    protected function addDocumentFieldsFromTyposcript(Document $document, array $indexingConfiguration, array $data) {
77
        $data = static::addVirtualContentFieldToRecord($document, $data);
78
79 19
        // mapping of record fields => solr document fields, resolving cObj
80
        foreach ($indexingConfiguration as $solrFieldName => $recordFieldName) {
81
            if (is_array($recordFieldName)) {
82 19
                // configuration for a content object, skipping
83 19
                continue;
84
            }
85 17
86
            if (!static::isAllowedToOverrideField($solrFieldName)) {
87
                throw new InvalidFieldNameException(
88 19
                    'Must not overwrite field .' . $solrFieldName,
89
                    1435441863
90
                );
91
            }
92
93
            $fieldValue = $this->resolveFieldValue($indexingConfiguration, $solrFieldName, $data);
94
95 19
            if (is_array($fieldValue)) {
96
                // multi value
97 19
                $document->setField($solrFieldName, $fieldValue);
98
            } else {
99 9
                if ($fieldValue !== '' && $fieldValue !== null) {
100 9
                    $document->setField($solrFieldName, $fieldValue);
101
                }
102
            }
103 19
        }
104 19
105
        return $document;
106
    }
107
108
109 19
    /**
110
     * Add's the content of the field 'content' from the solr document as virtual field __solr_content in the record,
111
     * to have it available in typoscript.
112
     *
113
     * @param Document $document
114
     * @param array $data
115
     * @return array
116
     */
117
    public static function addVirtualContentFieldToRecord(Document $document, array $data): array
118
    {
119
        if (isset($document['content'])) {
120
            $data['__solr_content'] = $document['content'];
121 59
            return $data;
122
        }
123 59
        return $data;
124 59
    }
125 40
126 40
    /**
127
     * Resolves a field to its value depending on its configuration.
128 19
     *
129
     * This enables you to configure the indexer to put the item/record through
130
     * cObj processing if wanted/needed. Otherwise the plain item/record value
131
     * is taken.
132
     *
133
     * @param array $indexingConfiguration Indexing configuration as defined in plugin.tx_solr_index.queue.[indexingConfigurationName].fields
134
     * @param string $solrFieldName A Solr field name that is configured in the indexing configuration
135
     * @param array $data A record or item's data
136
     * @return string The resolved string value to be indexed
137
     */
138
    protected function resolveFieldValue(
139
        array $indexingConfiguration,
140
        $solrFieldName,
141
        array $data
142
    ) {
143 19
        $contentObject = GeneralUtility::makeInstance(ContentObjectRenderer::class);
144
145
        if (isset($indexingConfiguration[$solrFieldName . '.'])) {
146
            // configuration found => need to resolve a cObj
147
148 19
            // need to change directory to make IMAGE content objects work in BE context
149
            // see http://blog.netzelf.de/lang/de/tipps-und-tricks/tslib_cobj-image-im-backend
150 19
            $backupWorkingDirectory = getcwd();
151
            chdir(Environment::getPublicPath() . '/');
152
153
            $contentObject->start($data, $this->type);
154
            $fieldValue = $contentObject->cObjGetSingle(
155 17
                $indexingConfiguration[$solrFieldName],
156 17
                $indexingConfiguration[$solrFieldName . '.']
157
            );
158 17
159 17
            chdir($backupWorkingDirectory);
160 17
161 17
            if ($this->isSerializedValue($indexingConfiguration,
162
                $solrFieldName)
163
            ) {
164 17
                $fieldValue = unserialize($fieldValue);
165
            }
166 17
        } elseif (substr($indexingConfiguration[$solrFieldName], 0,
167 17
                1) === '<'
168
        ) {
169 17
            $referencedTsPath = trim(substr($indexingConfiguration[$solrFieldName],
170
                1));
171 19
            $typoScriptParser = GeneralUtility::makeInstance(TypoScriptParser::class);
172 19
            // $name and $conf is loaded with the referenced values.
173
            list($name, $conf) = $typoScriptParser->getVal($referencedTsPath,
174
                $GLOBALS['TSFE']->tmpl->setup);
175
176
            // need to change directory to make IMAGE content objects work in BE context
177
            // see http://blog.netzelf.de/lang/de/tipps-und-tricks/tslib_cobj-image-im-backend
178
            $backupWorkingDirectory = getcwd();
179
            chdir(Environment::getPublicPath() . '/');
180
181
            $contentObject->start($data, $this->type);
182
            $fieldValue = $contentObject->cObjGetSingle($name, $conf);
183
184
            chdir($backupWorkingDirectory);
185
186
            if ($this->isSerializedValue($indexingConfiguration,
187
                $solrFieldName)
188
            ) {
189
                $fieldValue = unserialize($fieldValue);
190
            }
191
        } else {
192
            $fieldValue = $data[$indexingConfiguration[$solrFieldName]];
193
        }
194
195
        // detect and correct type for dynamic fields
196
197 19
        // find last underscore, substr from there, cut off last character (S/M)
198
        $fieldType = substr($solrFieldName, strrpos($solrFieldName, '_') + 1,
199
            -1);
200
        if (is_array($fieldValue)) {
201
            foreach ($fieldValue as $key => $value) {
202
                $fieldValue[$key] = $this->ensureFieldValueType($value,
203 19
                    $fieldType);
204 19
            }
205 19
        } else {
206 9
            $fieldValue = $this->ensureFieldValueType($fieldValue, $fieldType);
207 9
        }
208 9
209
        return $fieldValue;
210
    }
211 19
212
    // Utility methods
213
214 19
    /**
215
     * Uses a field's configuration to detect whether its value returned by a
216
     * content object is expected to be serialized and thus needs to be
217
     * unserialized.
218
     *
219
     * @param array $indexingConfiguration Current item's indexing configuration
220
     * @param string $solrFieldName Current field being indexed
221
     * @return bool TRUE if the value is expected to be serialized, FALSE otherwise
222
     */
223
    public static function isSerializedValue(array $indexingConfiguration, $solrFieldName)
224
    {
225
        $isSerialized = static::isSerializedResultFromRegisteredHook($indexingConfiguration, $solrFieldName);
226
        if ($isSerialized === true) {
227
            return $isSerialized;
228 60
        }
229
230 60
        $isSerialized = static::isSerializedResultFromCustomContentElement($indexingConfiguration, $solrFieldName);
231 59
        return $isSerialized;
232 1
    }
233
234
    /**
235 58
     * Checks if the response comes from a custom content element that returns a serialized value.
236 58
     *
237
     * @param array $indexingConfiguration
238
     * @param string $solrFieldName
239
     * @return bool
240
     */
241
    protected static function isSerializedResultFromCustomContentElement(array $indexingConfiguration, $solrFieldName): bool
242
    {
243
        $isSerialized = false;
244
245
        // SOLR_CLASSIFICATION - always returns serialized array
246 58
        if ($indexingConfiguration[$solrFieldName] == Classification::CONTENT_OBJECT_NAME) {
247
            $isSerialized = true;
248 58
        }
249
250
        // SOLR_MULTIVALUE - always returns serialized array
251 58
        if ($indexingConfiguration[$solrFieldName] == Multivalue::CONTENT_OBJECT_NAME) {
252 1
            $isSerialized = true;
253
        }
254
255
        // SOLR_RELATION - returns serialized array if multiValue option is set
256 58
        if ($indexingConfiguration[$solrFieldName] == Relation::CONTENT_OBJECT_NAME && !empty($indexingConfiguration[$solrFieldName . '.']['multiValue'])) {
257 2
            $isSerialized = true;
258
        }
259
260
        return $isSerialized;
261 58
    }
262 44
263
    /**
264
     * Checks registered hooks if a SerializedValueDetector detects a serialized response.
265 58
     *
266
     * @param array $indexingConfiguration
267
     * @param string $solrFieldName
268
     * @return bool
269
     */
270
    protected static function isSerializedResultFromRegisteredHook(array $indexingConfiguration, $solrFieldName)
271
    {
272
        if (!is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['detectSerializedValue'])) {
273
            return false;
274
        }
275 60
276
        foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['detectSerializedValue'] as $classReference) {
277 60
            $serializedValueDetector = GeneralUtility::makeInstance($classReference);
278 57
            if (!$serializedValueDetector instanceof SerializedValueDetector) {
279
                $message = get_class($serializedValueDetector) . ' must implement interface ' . SerializedValueDetector::class;
280
                throw new \UnexpectedValueException($message, 1404471741);
281 3
            }
282 2
283 2
            $isSerialized = (boolean)$serializedValueDetector->isSerializedValue($indexingConfiguration, $solrFieldName);
284 1
            if ($isSerialized) {
285 1
                return true;
286
            }
287
        }
288 1
    }
289 1
290 1
    /**
291
     * Makes sure a field's value matches a (dynamic) field's type.
292
     *
293 1
     * @param mixed $value Value to be added to a document
294
     * @param string $fieldType The dynamic field's type
295
     * @return mixed Returns the value in the correct format for the field type
296
     */
297
    protected function ensureFieldValueType($value, $fieldType)
298
    {
299
        switch ($fieldType) {
300
            case 'int':
301
            case 'tInt':
302 19
                $value = intval($value);
303
                break;
304
305 19
            case 'float':
306 19
            case 'tFloat':
307
                $value = floatval($value);
308
                break;
309
310 19
            // long and double do not exist in PHP
311 19
            // simply make sure it somehow looks like a number
312
            // <insert PHP rant here>
313
            case 'long':
314
            case 'tLong':
315
                // remove anything that's not a number or negative/minus sign
316
                $value = preg_replace('/[^0-9\\-]/', '', $value);
317
                if (trim($value) === '') {
318 19
                    $value = 0;
319 19
                }
320
                break;
321
            case 'double':
322
            case 'tDouble':
323
            case 'tDouble4':
324
                // as long as it's numeric we'll take it, int or float doesn't matter
325
                if (!is_numeric($value)) {
326 19
                    $value = 0;
327 19
                }
328 19
                break;
329
330
            default:
331
                // assume things are correct for non-dynamic fields
332
        }
333
334
        return $value;
335
    }
336
}
337