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 (#746)
by Alexander
03:26
created

DataHandler::initializeRepositories()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 6
rs 10
c 0
b 0
f 0
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\Object\ObjectManager;
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
     * @var ObjectManager
43
     */
44
    protected $objectManager;
45
46
    /**
47
     * @var DocumentRepository
48
     */
49
    protected $documentRepository;
50
51
    /**
52
     * Initialize the extbase repositories
53
     *
54
     * @return void
55
     */
56
    protected function initializeRepositories()
57
    {
58
        $this->objectManager = GeneralUtility::makeInstance(ObjectManager::class);
59
60
        $this->documentRepository = $this->objectManager->get(
61
            DocumentRepository::class
62
        );
63
    }
64
65
66
    /**
67
     * Field post-processing hook for the process_datamap() method.
68
     *
69
     * @access public
70
     *
71
     * @param string $status: 'new' or 'update'
72
     * @param string $table: The destination table
73
     * @param int $id: The uid of the record
74
     * @param array &$fieldArray: Array of field values
75
     *
76
     * @return void
77
     */
78
    public function processDatamap_postProcessFieldArray($status, $table, $id, &$fieldArray)
79
    {
80
        if ($status == 'new') {
81
            switch ($table) {
82
                    // Field post-processing for table "tx_dlf_documents".
83
                case 'tx_dlf_documents':
84
                    // Set sorting field if empty.
85
                    if (
86
                        empty($fieldArray['title_sorting'])
87
                        && !empty($fieldArray['title'])
88
                    ) {
89
                        $fieldArray['title_sorting'] = $fieldArray['title'];
90
                    }
91
                    break;
92
                    // Field post-processing for table "tx_dlf_metadata".
93
                case 'tx_dlf_metadata':
94
                    // Store field in index if it should appear in lists.
95
                    if (!empty($fieldArray['is_listed'])) {
96
                        $fieldArray['index_stored'] = 1;
97
                    }
98
                    // Index field in index if it should be used for auto-completion.
99
                    if (!empty($fieldArray['index_autocomplete'])) {
100
                        $fieldArray['index_indexed'] = 1;
101
                    }
102
                    // Field post-processing for tables "tx_dlf_metadata", "tx_dlf_collections", "tx_dlf_libraries" and "tx_dlf_structures".
103
                case 'tx_dlf_collections':
104
                case 'tx_dlf_libraries':
105
                case 'tx_dlf_structures':
106
                    // Set label as index name if empty.
107
                    if (
108
                        empty($fieldArray['index_name'])
109
                        && !empty($fieldArray['label'])
110
                    ) {
111
                        $fieldArray['index_name'] = $fieldArray['label'];
112
                    }
113
                    // Set index name as label if empty.
114
                    if (
115
                        empty($fieldArray['label'])
116
                        && !empty($fieldArray['index_name'])
117
                    ) {
118
                        $fieldArray['label'] = $fieldArray['index_name'];
119
                    }
120
                    // Ensure that index names don't get mixed up with sorting values.
121
                    if (substr($fieldArray['index_name'], -8) == '_sorting') {
122
                        $fieldArray['index_name'] .= '0';
123
                    }
124
                    break;
125
                    // Field post-processing for table "tx_dlf_solrcores".
126
                case 'tx_dlf_solrcores':
127
                    // Create new Solr core.
128
                    $fieldArray['index_name'] = Solr::createCore($fieldArray['index_name']);
129
                    if (empty($fieldArray['index_name'])) {
130
                        $this->logger->error('Could not create new Apache Solr core');
131
                    }
132
                    break;
133
            }
134
        } elseif ($status == 'update') {
135
            switch ($table) {
136
                    // Field post-processing for table "tx_dlf_metadata".
137
                case 'tx_dlf_metadata':
138
                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
139
                        ->getQueryBuilderForTable($table);
140
141
                    // Store field in index if it should appear in lists.
142
                    if (!empty($fieldArray['is_listed'])) {
143
                        $fieldArray['index_stored'] = 1;
144
                    }
145
                    if (
146
                        isset($fieldArray['index_stored'])
147
                        && $fieldArray['index_stored'] == 0
148
                        && !isset($fieldArray['is_listed'])
149
                    ) {
150
                        // Get current configuration.
151
                        $result = $queryBuilder
152
                            ->select($table . '.is_listed AS is_listed')
153
                            ->from($table)
154
                            ->where(
155
                                $queryBuilder->expr()->eq($table . '.uid', intval($id)),
156
                                Helper::whereExpression($table)
157
                            )
158
                            ->setMaxResults(1)
159
                            ->execute();
160
161
                        if ($resArray = $result->fetch()) {
162
                            // Reset storing to current.
163
                            $fieldArray['index_stored'] = $resArray['is_listed'];
164
                        }
165
                    }
166
                    // Index field in index if it should be used for auto-completion.
167
                    if (!empty($fieldArray['index_autocomplete'])) {
168
                        $fieldArray['index_indexed'] = 1;
169
                    }
170
                    if (
171
                        isset($fieldArray['index_indexed'])
172
                        && $fieldArray['index_indexed'] == 0
173
                        && !isset($fieldArray['index_autocomplete'])
174
                    ) {
175
                        // Get current configuration.
176
                        $result = $queryBuilder
177
                            ->select($table . '.index_autocomplete AS index_autocomplete')
178
                            ->from($table)
179
                            ->where(
180
                                $queryBuilder->expr()->eq($table . '.uid', intval($id)),
181
                                Helper::whereExpression($table)
182
                            )
183
                            ->setMaxResults(1)
184
                            ->execute();
185
186
                        if ($resArray = $result->fetch()) {
187
                            // Reset indexing to current.
188
                            $fieldArray['index_indexed'] = $resArray['index_autocomplete'];
189
                        }
190
                    }
191
                    break;
192
            }
193
        }
194
    }
195
196
    /**
197
     * After database operations hook for the process_datamap() method.
198
     *
199
     * @access public
200
     *
201
     * @param string $status: 'new' or 'update'
202
     * @param string $table: The destination table
203
     * @param int $id: The uid of the record
204
     * @param array &$fieldArray: Array of field values
205
     *
206
     * @return void
207
     */
208
    public function processDatamap_afterDatabaseOperations($status, $table, $id, &$fieldArray)
209
    {
210
        $this->initializeRepositories();
211
212
        if ($status == 'update') {
213
            switch ($table) {
214
                    // After database operations for table "tx_dlf_documents".
215
                case 'tx_dlf_documents':
216
                    // Delete/reindex document in Solr if "hidden" status or collections have changed.
217
                    if (
218
                        isset($fieldArray['hidden'])
219
                        || isset($fieldArray['collections'])
220
                    ) {
221
                        // Get Solr-Core.
222
                        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
223
                            ->getQueryBuilderForTable('tx_dlf_solrcores');
224
225
                        $result = $queryBuilder
226
                            ->select(
227
                                'tx_dlf_solrcores.uid AS core',
228
                                'tx_dlf_solrcores.index_name',
229
                                'tx_dlf_documents_join.hidden AS hidden'
230
                            )
231
                            ->innerJoin(
232
                                'tx_dlf_solrcores',
233
                                'tx_dlf_documents',
234
                                'tx_dlf_documents_join',
235
                                $queryBuilder->expr()->eq(
236
                                    'tx_dlf_documents_join.solrcore',
237
                                    'tx_dlf_solrcores.uid'
238
                                )
239
                            )
240
                            ->from('tx_dlf_solrcores')
241
                            ->where(
242
                                $queryBuilder->expr()->eq(
243
                                    'tx_dlf_documents_join.uid',
244
                                    intval($id)
245
                                )
246
                            )
247
                            ->setMaxResults(1)
248
                            ->execute();
249
250
                        $resArray = $result->fetch();
251
                        if ($resArray !== null) {
252
                            if ($resArray['hidden']) {
253
                                // Establish Solr connection.
254
                                $solr = Solr::getInstance($resArray['core']);
255
                                if ($solr->ready) {
256
                                    // Delete Solr document.
257
                                    $updateQuery = $solr->service->createUpdate();
258
                                    $updateQuery->addDeleteQuery('uid:' . $id);
259
                                    $updateQuery->addCommit();
260
                                    $solr->service->update($updateQuery);
261
                                }
262
                            } else {
263
                                // Reindex document.
264
                                $document = $this->documentRepository->findByUid($id);
265
                                $doc = Doc::getInstance($document->getLocation(), ['storagePid' => $document->getPid()], true);
266
                                if ($document !== null && $doc !== null) {
267
                                    $document->setDoc($doc);
268
                                    Indexer::add($document, $resArray['core']);
269
                                } else {
270
                                    $this->logger->error('Failed to re-index document with UID ' . $id);
271
                                }
272
                            }
273
                        }
274
                    }
275
                break;
276
            }
277
        }
278
    }
279
280
    /**
281
     * Post-processing hook for the process_cmdmap() method.
282
     *
283
     * @access public
284
     *
285
     * @param string $command: 'move', 'copy', 'localize', 'inlineLocalizeSynchronize', 'delete' or 'undelete'
286
     * @param string $table: The destination table
287
     * @param int $id: The uid of the record
288
     *
289
     * @return void
290
     */
291
    public function processCmdmap_postProcess($command, $table, $id)
292
    {
293
        if (
294
            in_array($command, ['move', 'delete', 'undelete'])
295
            && $table == 'tx_dlf_documents'
296
        ) {
297
            // Get Solr core.
298
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
299
                ->getQueryBuilderForTable('tx_dlf_solrcores');
300
            // Record in "tx_dlf_documents" is already deleted at this point.
301
            $queryBuilder
302
                ->getRestrictions()
303
                ->removeByType(DeletedRestriction::class);
304
305
            $result = $queryBuilder
306
                ->select(
307
                    'tx_dlf_solrcores.uid AS core'
308
                )
309
                ->innerJoin(
310
                    'tx_dlf_solrcores',
311
                    'tx_dlf_documents',
312
                    'tx_dlf_documents_join',
313
                    $queryBuilder->expr()->eq(
314
                        'tx_dlf_documents_join.solrcore',
315
                        'tx_dlf_solrcores.uid'
316
                    )
317
                )
318
                ->from('tx_dlf_solrcores')
319
                ->where(
320
                    $queryBuilder->expr()->eq(
321
                        'tx_dlf_documents_join.uid',
322
                        intval($id)
323
                    )
324
                )
325
                ->setMaxResults(1)
326
                ->execute();
327
328
            $allResults = $result->fetchAll();
329
330
            if (count($allResults) == 1) {
331
                $resArray = $allResults[0];
332
                switch ($command) {
333
                    case 'move':
334
                    case 'delete':
335
                        // Establish Solr connection.
336
                        $solr = Solr::getInstance($resArray['core']);
337
                        if ($solr->ready) {
338
                            // Delete Solr document.
339
                            $updateQuery = $solr->service->createUpdate();
340
                            $updateQuery->addDeleteQuery('uid:' . $id);
341
                            $updateQuery->addCommit();
342
                            $solr->service->update($updateQuery);
343
                            if ($command == 'delete') {
344
                                break;
345
                            }
346
                        }
347
                    case 'undelete':
348
                        // Reindex document.
349
                        $doc = Doc::getInstance($id);
350
                        if ($doc->ready) {
351
                            Indexer::add($doc, $resArray['core']);
0 ignored issues
show
Bug introduced by
$doc of type Kitodo\Dlf\Common\MetsDocument is incompatible with the type Kitodo\Dlf\Domain\Model\Document expected by parameter $document of Kitodo\Dlf\Common\Indexer::add(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

351
                            Indexer::add(/** @scrutinizer ignore-type */ $doc, $resArray['core']);
Loading history...
352
                        } else {
353
                            $this->logger->error('Failed to re-index document with UID ' . $id);
354
                        }
355
                        break;
356
                }
357
            }
358
        }
359
        if (
360
            $command === 'delete'
361
            && $table == 'tx_dlf_solrcores'
362
        ) {
363
            // Is core deletion allowed in extension configuration?
364
            $extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get('dlf');
365
            if (!empty($extConf['solrAllowCoreDelete'])) {
366
                // Delete core from Apache Solr as well.
367
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
368
                    ->getQueryBuilderForTable('tx_dlf_solrcores');
369
                // Record in "tx_dlf_solrcores" is already deleted at this point.
370
                $queryBuilder
371
                    ->getRestrictions()
372
                    ->removeByType(DeletedRestriction::class);
373
374
                $result = $queryBuilder
375
                    ->select(
376
                        'tx_dlf_solrcores.index_name AS core'
377
                    )
378
                    ->from('tx_dlf_solrcores')
379
                    ->where($queryBuilder->expr()->eq('tx_dlf_solrcores.uid', intval($id)))
380
                    ->setMaxResults(1)
381
                    ->execute();
382
383
                $allResults = $result->fetchAll();
384
385
                if (count($allResults) == 1) {
386
                    $resArray = $allResults[0];
387
                    // Establish Solr connection.
388
                    $solr = Solr::getInstance();
389
                    if ($solr->ready) {
390
                        // Delete Solr core.
391
                        $query = $solr->service->createCoreAdmin();
392
                        $action = $query->createUnload();
393
                        $action->setCore($resArray['core']);
394
                        $action->setDeleteDataDir(true);
395
                        $action->setDeleteIndex(true);
396
                        $action->setDeleteInstanceDir(true);
397
                        $query->setAction($action);
398
                        try {
399
                            $response = $solr->service->coreAdmin($query);
400
                            if ($response->getWasSuccessful()) {
401
                                return;
402
                            }
403
                        } catch (\Exception $e) {
404
                            // Nothing to do here.
405
                        }
406
                    }
407
                    $this->logger->warning('Core ' . $resArray['core'] . ' could not be deleted from Apache Solr');
408
                }
409
            }
410
        }
411
    }
412
}
413