Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Pull Request — dev-extbase-fluid (#757)
by Alexander
05:02 queued 02:23
created

DataHandler::processCmdmap_postProcess()   D

Complexity

Conditions 18
Paths 152

Size

Total Lines 113
Code Lines 79

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 18
eloc 79
c 1
b 0
f 0
nc 152
nop 3
dl 0
loc 113
rs 4.4333

How to fix   Long Method    Complexity   

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
3
/**
4
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
5
 *
6
 * This file is part of the Kitodo and TYPO3 projects.
7
 *
8
 * @license GNU General Public License version 3 or later.
9
 * For the full copyright and license information, please read the
10
 * LICENSE.txt file that was distributed with this source code.
11
 */
12
13
namespace Kitodo\Dlf\Hooks;
14
15
use Kitodo\Dlf\Common\Doc;
16
use Kitodo\Dlf\Common\Helper;
17
use Kitodo\Dlf\Common\Indexer;
18
use Kitodo\Dlf\Common\Solr;
19
use Kitodo\Dlf\Domain\Repository\DocumentRepository;
20
use Kitodo\Dlf\Domain\Model\Document;
21
use Psr\Log\LoggerAwareInterface;
22
use Psr\Log\LoggerAwareTrait;
23
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
24
use TYPO3\CMS\Core\Database\ConnectionPool;
25
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
26
use TYPO3\CMS\Core\Utility\GeneralUtility;
27
use TYPO3\CMS\Extbase\Annotation\Inject;
28
29
/**
30
 * Hooks and helper for \TYPO3\CMS\Core\DataHandling\DataHandler
31
 *
32
 * @author Sebastian Meyer <[email protected]>
33
 * @package TYPO3
34
 * @subpackage dlf
35
 * @access public
36
 */
37
class DataHandler implements LoggerAwareInterface
38
{
39
    use LoggerAwareTrait;
40
41
    /**
42
     * @Inject
43
     * @var DocumentRepository
44
     */
45
    protected $documentRepository;
46
47
    /**
48
     * Field post-processing hook for the process_datamap() method.
49
     *
50
     * @access public
51
     *
52
     * @param string $status: 'new' or 'update'
53
     * @param string $table: The destination table
54
     * @param int $id: The uid of the record
55
     * @param array &$fieldArray: Array of field values
56
     *
57
     * @return void
58
     */
59
    public function processDatamap_postProcessFieldArray($status, $table, $id, &$fieldArray)
60
    {
61
        if ($status == 'new') {
62
            switch ($table) {
63
                    // Field post-processing for table "tx_dlf_documents".
64
                case 'tx_dlf_documents':
65
                    // Set sorting field if empty.
66
                    if (
67
                        empty($fieldArray['title_sorting'])
68
                        && !empty($fieldArray['title'])
69
                    ) {
70
                        $fieldArray['title_sorting'] = $fieldArray['title'];
71
                    }
72
                    break;
73
                    // Field post-processing for table "tx_dlf_metadata".
74
                case 'tx_dlf_metadata':
75
                    // Store field in index if it should appear in lists.
76
                    if (!empty($fieldArray['is_listed'])) {
77
                        $fieldArray['index_stored'] = 1;
78
                    }
79
                    // Index field in index if it should be used for auto-completion.
80
                    if (!empty($fieldArray['index_autocomplete'])) {
81
                        $fieldArray['index_indexed'] = 1;
82
                    }
83
                    // Field post-processing for tables "tx_dlf_metadata", "tx_dlf_collections", "tx_dlf_libraries" and "tx_dlf_structures".
84
                case 'tx_dlf_collections':
85
                case 'tx_dlf_libraries':
86
                case 'tx_dlf_structures':
87
                    // Set label as index name if empty.
88
                    if (
89
                        empty($fieldArray['index_name'])
90
                        && !empty($fieldArray['label'])
91
                    ) {
92
                        $fieldArray['index_name'] = $fieldArray['label'];
93
                    }
94
                    // Set index name as label if empty.
95
                    if (
96
                        empty($fieldArray['label'])
97
                        && !empty($fieldArray['index_name'])
98
                    ) {
99
                        $fieldArray['label'] = $fieldArray['index_name'];
100
                    }
101
                    // Ensure that index names don't get mixed up with sorting values.
102
                    if (substr($fieldArray['index_name'], -8) == '_sorting') {
103
                        $fieldArray['index_name'] .= '0';
104
                    }
105
                    break;
106
                    // Field post-processing for table "tx_dlf_solrcores".
107
                case 'tx_dlf_solrcores':
108
                    // Create new Solr core.
109
                    $fieldArray['index_name'] = Solr::createCore($fieldArray['index_name']);
110
                    if (empty($fieldArray['index_name'])) {
111
                        $this->logger->error('Could not create new Apache Solr core');
112
                    }
113
                    break;
114
            }
115
        } elseif ($status == 'update') {
116
            switch ($table) {
117
                    // Field post-processing for table "tx_dlf_metadata".
118
                case 'tx_dlf_metadata':
119
                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
120
                        ->getQueryBuilderForTable($table);
121
122
                    // Store field in index if it should appear in lists.
123
                    if (!empty($fieldArray['is_listed'])) {
124
                        $fieldArray['index_stored'] = 1;
125
                    }
126
                    if (
127
                        isset($fieldArray['index_stored'])
128
                        && $fieldArray['index_stored'] == 0
129
                        && !isset($fieldArray['is_listed'])
130
                    ) {
131
                        // Get current configuration.
132
                        $result = $queryBuilder
133
                            ->select($table . '.is_listed AS is_listed')
134
                            ->from($table)
135
                            ->where(
136
                                $queryBuilder->expr()->eq($table . '.uid', intval($id)),
137
                                Helper::whereExpression($table)
138
                            )
139
                            ->setMaxResults(1)
140
                            ->execute();
141
142
                        if ($resArray = $result->fetch()) {
143
                            // Reset storing to current.
144
                            $fieldArray['index_stored'] = $resArray['is_listed'];
145
                        }
146
                    }
147
                    // Index field in index if it should be used for auto-completion.
148
                    if (!empty($fieldArray['index_autocomplete'])) {
149
                        $fieldArray['index_indexed'] = 1;
150
                    }
151
                    if (
152
                        isset($fieldArray['index_indexed'])
153
                        && $fieldArray['index_indexed'] == 0
154
                        && !isset($fieldArray['index_autocomplete'])
155
                    ) {
156
                        // Get current configuration.
157
                        $result = $queryBuilder
158
                            ->select($table . '.index_autocomplete AS index_autocomplete')
159
                            ->from($table)
160
                            ->where(
161
                                $queryBuilder->expr()->eq($table . '.uid', intval($id)),
162
                                Helper::whereExpression($table)
163
                            )
164
                            ->setMaxResults(1)
165
                            ->execute();
166
167
                        if ($resArray = $result->fetch()) {
168
                            // Reset indexing to current.
169
                            $fieldArray['index_indexed'] = $resArray['index_autocomplete'];
170
                        }
171
                    }
172
                    break;
173
            }
174
        }
175
    }
176
177
    /**
178
     * After database operations hook for the process_datamap() method.
179
     *
180
     * @access public
181
     *
182
     * @param string $status: 'new' or 'update'
183
     * @param string $table: The destination table
184
     * @param int $id: The uid of the record
185
     * @param array &$fieldArray: Array of field values
186
     *
187
     * @return void
188
     */
189
    public function processDatamap_afterDatabaseOperations($status, $table, $id, &$fieldArray)
190
    {
191
        if ($status == 'update') {
192
            switch ($table) {
193
                    // After database operations for table "tx_dlf_documents".
194
                case 'tx_dlf_documents':
195
                    // Delete/reindex document in Solr if "hidden" status or collections have changed.
196
                    if (
197
                        isset($fieldArray['hidden'])
198
                        || isset($fieldArray['collections'])
199
                    ) {
200
                        // Get Solr-Core.
201
                        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
202
                            ->getQueryBuilderForTable('tx_dlf_solrcores');
203
204
                        $result = $queryBuilder
205
                            ->select(
206
                                'tx_dlf_solrcores.uid AS core',
207
                                'tx_dlf_solrcores.index_name',
208
                                'tx_dlf_documents_join.hidden AS hidden'
209
                            )
210
                            ->innerJoin(
211
                                'tx_dlf_solrcores',
212
                                'tx_dlf_documents',
213
                                'tx_dlf_documents_join',
214
                                $queryBuilder->expr()->eq(
215
                                    'tx_dlf_documents_join.solrcore',
216
                                    'tx_dlf_solrcores.uid'
217
                                )
218
                            )
219
                            ->from('tx_dlf_solrcores')
220
                            ->where(
221
                                $queryBuilder->expr()->eq(
222
                                    'tx_dlf_documents_join.uid',
223
                                    intval($id)
224
                                )
225
                            )
226
                            ->setMaxResults(1)
227
                            ->execute();
228
229
                        if ($resArray = $result->fetch()) {
230
                            if ($resArray['hidden']) {
231
                                // Establish Solr connection.
232
                                $solr = Solr::getInstance($resArray['core']);
233
                                if ($solr->ready) {
234
                                    // Delete Solr document.
235
                                    $updateQuery = $solr->service->createUpdate();
236
                                    $updateQuery->addDeleteQuery('uid:' . $id);
237
                                    $updateQuery->addCommit();
238
                                    $solr->service->update($updateQuery);
239
                                }
240
                            } else {
241
                                // Reindex document.
242
                                $document = $this->documentRepository->findByUid($id);
243
                                $doc = Doc::getInstance($document->getLocation(), ['storagePid' => $document->getPid()], true);
244
                                if ($document !== null && $doc !== null) {
245
                                    $document->setDoc($doc);
246
                                    Indexer::add($document);
247
                                } else {
248
                                    $this->logger->error('Failed to re-index document with UID ' . $id);
249
                                }
250
                            }
251
                        }
252
                    }
253
                break;
254
            }
255
        }
256
    }
257
258
    /**
259
     * Post-processing hook for the process_cmdmap() method.
260
     *
261
     * @access public
262
     *
263
     * @param string $command: 'move', 'copy', 'localize', 'inlineLocalizeSynchronize', 'delete' or 'undelete'
264
     * @param string $table: The destination table
265
     * @param int $id: The uid of the record
266
     *
267
     * @return void
268
     */
269
    public function processCmdmap_postProcess($command, $table, $id)
270
    {
271
        if (
272
            in_array($command, ['move', 'delete', 'undelete'])
273
            && $table == 'tx_dlf_documents'
274
        ) {
275
            // Get Solr core.
276
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
277
                ->getQueryBuilderForTable('tx_dlf_solrcores');
278
            // Record in "tx_dlf_documents" is already deleted at this point.
279
            $queryBuilder
280
                ->getRestrictions()
281
                ->removeByType(DeletedRestriction::class);
282
283
            $result = $queryBuilder
284
                ->select(
285
                    'tx_dlf_solrcores.uid AS core'
286
                )
287
                ->innerJoin(
288
                    'tx_dlf_solrcores',
289
                    'tx_dlf_documents',
290
                    'tx_dlf_documents_join',
291
                    $queryBuilder->expr()->eq(
292
                        'tx_dlf_documents_join.solrcore',
293
                        'tx_dlf_solrcores.uid'
294
                    )
295
                )
296
                ->from('tx_dlf_solrcores')
297
                ->where(
298
                    $queryBuilder->expr()->eq(
299
                        'tx_dlf_documents_join.uid',
300
                        intval($id)
301
                    )
302
                )
303
                ->setMaxResults(1)
304
                ->execute();
305
306
            if ($resArray = $result->fetch()) {
307
                switch ($command) {
308
                    case 'move':
309
                    case 'delete':
310
                        // Establish Solr connection.
311
                        $solr = Solr::getInstance($resArray['core']);
312
                        if ($solr->ready) {
313
                            // Delete Solr document.
314
                            $updateQuery = $solr->service->createUpdate();
315
                            $updateQuery->addDeleteQuery('uid:' . $id);
316
                            $updateQuery->addCommit();
317
                            $solr->service->update($updateQuery);
318
                            if ($command == 'delete') {
319
                                break;
320
                            }
321
                        }
322
                    case 'undelete':
323
                        // Reindex document.
324
                        $document = $this->documentRepository->findByUid($id);
325
                        $doc = Doc::getInstance($document->getLocation(), ['storagePid' => $document->getPid()], true);
326
                        if ($document !== null && $doc !== null) {
327
                            $document->setDoc($doc);
328
                            Indexer::add($document);
329
                        } else {
330
                            $this->logger->error('Failed to re-index document with UID ' . $id);
331
                        }
332
                        break;
333
                }
334
            }
335
        }
336
        if (
337
            $command === 'delete'
338
            && $table == 'tx_dlf_solrcores'
339
        ) {
340
            // Is core deletion allowed in extension configuration?
341
            $extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get('dlf');
342
            if (!empty($extConf['solrAllowCoreDelete'])) {
343
                // Delete core from Apache Solr as well.
344
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
345
                    ->getQueryBuilderForTable('tx_dlf_solrcores');
346
                // Record in "tx_dlf_solrcores" is already deleted at this point.
347
                $queryBuilder
348
                    ->getRestrictions()
349
                    ->removeByType(DeletedRestriction::class);
350
351
                $result = $queryBuilder
352
                    ->select(
353
                        'tx_dlf_solrcores.index_name AS core'
354
                    )
355
                    ->from('tx_dlf_solrcores')
356
                    ->where($queryBuilder->expr()->eq('tx_dlf_solrcores.uid', intval($id)))
357
                    ->setMaxResults(1)
358
                    ->execute();
359
360
                if ($resArray = $result->fetch()) {
361
                    // Establish Solr connection.
362
                    $solr = Solr::getInstance();
363
                    if ($solr->ready) {
364
                        // Delete Solr core.
365
                        $query = $solr->service->createCoreAdmin();
366
                        $action = $query->createUnload();
367
                        $action->setCore($resArray['core']);
368
                        $action->setDeleteDataDir(true);
369
                        $action->setDeleteIndex(true);
370
                        $action->setDeleteInstanceDir(true);
371
                        $query->setAction($action);
372
                        try {
373
                            $response = $solr->service->coreAdmin($query);
374
                            if ($response->getWasSuccessful()) {
375
                                return;
376
                            }
377
                        } catch (\Exception $e) {
378
                            // Nothing to do here.
379
                        }
380
                    }
381
                    $this->logger->warning('Core ' . $resArray['core'] . ' could not be deleted from Apache Solr');
382
                }
383
            }
384
        }
385
    }
386
}
387