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
Branch master (f6821b)
by Sebastian
03:23
created

ReindexCommand::getDocumentsToProceed()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 57
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 40
c 1
b 0
f 1
dl 0
loc 57
rs 9.28
cc 2
nc 2
nop 2

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
3
namespace Kitodo\Dlf\Command;
4
5
/**
6
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
7
 *
8
 * This file is part of the Kitodo and TYPO3 projects.
9
 *
10
 * @license GNU General Public License version 3 or later.
11
 * For the full copyright and license information, please read the
12
 * LICENSE.txt file that was distributed with this source code.
13
 */
14
15
use Symfony\Component\Console\Command\Command;
16
use Symfony\Component\Console\Input\InputInterface;
17
use Symfony\Component\Console\Input\InputOption;
18
use Symfony\Component\Console\Output\OutputInterface;
19
use Symfony\Component\Console\Style\SymfonyStyle;
20
use TYPO3\CMS\Core\Core\Bootstrap;
21
use TYPO3\CMS\Core\Utility\GeneralUtility;
22
use TYPO3\CMS\Core\Utility\MathUtility;
23
use TYPO3\CMS\Core\Database\ConnectionPool;
24
use TYPO3\CMS\Core\Database\Connection;
25
use Kitodo\Dlf\Common\Document;
26
27
/**
28
 * Reindex a collection into database and Solr.
29
 */
30
class ReindexCommand extends Command
31
{
32
    /**
33
     * Configure the command by defining the name, options and arguments
34
     */
35
    public function configure()
36
    {
37
        $this
38
            ->setDescription('Reindex a collection into database and Solr.')
39
            ->setHelp('')
40
            ->addOption(
41
                'dry-run',
42
                NULL,
43
                InputOption::VALUE_NONE,
44
                'If this option is set, the files will not actually be processed but the location URI is shown.'
45
            )
46
            ->addOption(
47
                'coll',
48
                'c',
49
                InputOption::VALUE_REQUIRED,
50
                'UID of the collection.'
51
            )
52
            ->addOption(
53
                'pid',
54
                'p',
55
                InputOption::VALUE_REQUIRED,
56
                'UID of the page the documents should be added to.'
57
            )
58
            ->addOption(
59
                'solr',
60
                's',
61
                InputOption::VALUE_REQUIRED,
62
                '[UID|index_name] of the Solr core the document should be added to.'
63
            )
64
            ->addOption(
65
                'all',
66
                'a',
67
                InputOption::VALUE_NONE,
68
                'Reindex all documents on the given page.'
69
            );
70
    }
71
72
    /**
73
     * Executes the command to index the given document to db and solr.
74
     *
75
     * @param InputInterface $input
76
     * @param OutputInterface $output
77
     */
78
    protected function execute(InputInterface $input, OutputInterface $output)
79
    {
80
        // Make sure the _cli_ user is loaded
81
        Bootstrap::getInstance()->initializeBackendAuthentication();
82
83
        $dryRun = $input->getOption('dry-run') != FALSE ? TRUE : FALSE;
84
85
        $io = new SymfonyStyle($input, $output);
86
        $io->title($this->getDescription());
87
88
        $startingPoint = 0;
89
        if (MathUtility::canBeInterpretedAsInteger($input->getOption('pid'))) {
90
            $startingPoint = MathUtility::forceIntegerInRange((int) $input->getOption('pid'), 0);
91
        }
92
        if ($startingPoint == 0) {
93
            $io->error('ERROR: No valid PID (' . $startingPoint . ') given.');
94
            exit(1);
95
        }
96
97
        if (
98
            !empty($input->getOption('solr'))
99
            && !is_array($input->getOption('solr'))
100
        ) {
101
            $allSolrCores = $this->getSolrCores($startingPoint);
102
            if (MathUtility::canBeInterpretedAsInteger($input->getOption('solr'))) {
103
                $solrCoreUid = MathUtility::forceIntegerInRange((int) $input->getOption('solr'), 0);
104
            } else {
105
                $solrCoreUid = $allSolrCores[$input->getOption('solr')];
106
            }
107
            // Abort if solrCoreUid is empty or not in the array of allowed solr cores.
108
            if (empty($solrCoreUid) || !in_array($solrCoreUid, $allSolrCores)) {
109
                $output_solrCores = [];
110
                foreach ($allSolrCores as $index_name => $uid) {
111
                    $output_solrCores[] = $uid . ' : ' . $index_name;
112
                }
113
                if (empty($output_solrCores)) {
114
                    $io->error('ERROR: No valid Solr core ("' . $input->getOption('solr') . '") given. No valid cores found on PID ' . $startingPoint . ".\n");
115
                    exit(1);
116
                } else {
117
                    $io->error('ERROR: No valid Solr core ("' . $input->getOption('solr') . '") given. ' . "Valid cores are (<uid>:<index_name>):\n" . implode("\n", $output_solrCores) . "\n");
118
                    exit(1);
119
                }
120
            }
121
        } else {
122
            $io->error('ERROR: Required parameter --solr|-s is missing or array.');
123
            exit(1);
124
        }
125
126
        if (!empty($input->getOption('all'))) {
127
            // Get all documents.
128
            $documents = $this->getAllDocuments($startingPoint);
129
        } elseif (
130
            !empty($input->getOption('coll'))
131
            && !is_array($input->getOption('coll'))
132
        ) {
133
            // "coll" may be a single integer or a comma-separated list of integers.
134
            if (empty(array_filter(GeneralUtility::intExplode(',', $input->getOption('coll'), TRUE)))) {
1 ignored issue
show
Bug introduced by
It seems like $input->getOption('coll') can also be of type string[]; however, parameter $string of TYPO3\CMS\Core\Utility\G...alUtility::intExplode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

134
            if (empty(array_filter(GeneralUtility::intExplode(',', /** @scrutinizer ignore-type */ $input->getOption('coll'), TRUE)))) {
Loading history...
135
                $io->error('ERROR: Parameter --coll|-c is not a valid comma-separated list of collection UIDs.');
136
                exit(1);
137
            }
138
            $documents = $this->getDocumentsToProceed($input->getOption('coll'), $startingPoint);
139
        } else {
140
            $io->error('ERROR: One of parameters --all|-a or --coll|-c must be given.');
141
            exit(1);
142
        }
143
144
        foreach ($documents as $id => $document) {
145
            $doc = Document::getInstance($document, $startingPoint, TRUE);
146
            if ($doc->ready) {
147
                if ($dryRun) {
148
                    $io->writeln('DRY RUN: Would index ' . $id . '/' . count($documents) . ' ' . $doc->uid . ' ("' . $doc->location . '") on UID ' . $startingPoint . ' and Solr core ' . $solrCoreUid . '.');
149
                } else {
150
                    if ($io->isVerbose()) {
151
                        $io->writeln(date('Y-m-d H:i:s') . ' Indexing ' . $id . '/' . count($documents) . ' ' . $doc->uid . ' ("' . $doc->location . '") on UID ' . $startingPoint . ' and Solr core ' . $solrCoreUid . '.');
152
                    }
153
                    // ...and save it to the database...
154
                    if (!$doc->save($startingPoint, $solrCoreUid)) {
155
                        $io->error('ERROR: Document "' . $id . '" not saved and indexed.');
156
                    }
157
                }
158
            } else {
159
                $io->error('ERROR: Document "' . $id . '" could not be loaded.');
160
            }
161
            // Clear document registry to prevent memory exhaustion.
162
            Document::clearRegistry();
163
        }
164
165
        $io->success('All done!');
166
    }
167
168
169
    /**
170
     * Fetches all records of tx_dlf_solrcores on given page.
171
     *
172
     * @param int $pageId the uid of the solr record (can also be 0)
173
     *
174
     * @return array array of valid solr cores
175
     */
176
    protected function getSolrCores(int $pageId): array
177
    {
178
        /** @var QueryBuilder $queryBuilder */
179
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
180
            ->getQueryBuilderForTable('tx_dlf_solrcores');
181
182
        $solrCores = [];
183
        $pageId = (int) $pageId;
184
        $result = $queryBuilder
185
            ->select('uid', 'index_name')
186
            ->from('tx_dlf_solrcores')
187
            ->where(
188
                $queryBuilder->expr()->eq(
189
                    'pid',
190
                    $queryBuilder->createNamedParameter($pageId, \PDO::PARAM_INT)
191
                )
192
            )
193
            ->execute();
194
195
        while ($record = $result->fetch()) {
196
            $solrCores[$record['index_name']] = $record['uid'];
197
        }
198
199
        return $solrCores;
200
    }
201
202
    /**
203
     * Fetches all documents with given collection.
204
     *
205
     * @param string $collId a comma separated list of collection uids
206
     * @param int $pageId the uid of the solr record
207
     *
208
     * @return array array of valid solr cores
209
     */
210
    protected function getDocumentsToProceed(string $collIds, int $pageId): array
211
    {
212
        /** @var QueryBuilder $queryBuilder */
213
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
214
            ->getQueryBuilderForTable('tx_dlf_documents');
215
216
        $documents = [];
217
        $pageId = (int) $pageId;
218
        $result = $queryBuilder
219
            ->select('tx_dlf_documents.uid')
220
            ->from('tx_dlf_documents')
221
            ->join(
222
                'tx_dlf_documents',
223
                'tx_dlf_relations',
224
                'tx_dlf_relations_joins',
225
                $queryBuilder->expr()->eq(
226
                    'tx_dlf_relations_joins.uid_local',
227
                    'tx_dlf_documents.uid'
228
                )
229
            )
230
            ->join(
231
                'tx_dlf_relations_joins',
232
                'tx_dlf_collections',
233
                'tx_dlf_collections_join',
234
                $queryBuilder->expr()->eq(
235
                    'tx_dlf_relations_joins.uid_foreign',
236
                    'tx_dlf_collections_join.uid'
237
                )
238
            )
239
            ->where(
240
                $queryBuilder->expr()->andX(
241
                    $queryBuilder->expr()->in(
242
                        'tx_dlf_collections_join.uid',
243
                        $queryBuilder->createNamedParameter(
244
                            GeneralUtility::intExplode(',', $collIds, TRUE),
245
                            Connection::PARAM_INT_ARRAY
246
                        )
247
                    ),
248
                    $queryBuilder->expr()->eq(
249
                        'tx_dlf_collections_join.pid',
250
                        $queryBuilder->createNamedParameter($pageId, Connection::PARAM_INT)
251
                    ),
252
                    $queryBuilder->expr()->eq(
253
                        'tx_dlf_relations_joins.ident',
254
                        $queryBuilder->createNamedParameter('docs_colls')
255
                    )
256
                )
257
            )
258
            ->groupBy('tx_dlf_documents.uid')
259
            ->orderBy('tx_dlf_documents.uid', 'ASC')
260
            ->execute();
261
262
        while ($record = $result->fetch()) {
263
            $documents[] = $record['uid'];
264
        }
265
266
        return $documents;
267
    }
268
269
    /**
270
     * Fetches all documents of given page.
271
     *
272
     * @param int $pageId the uid of the solr record
273
     *
274
     * @return array array of valid solr cores
275
     */
276
    protected function getAllDocuments(int $pageId): array
277
    {
278
        /** @var QueryBuilder $queryBuilder */
279
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
280
            ->getQueryBuilderForTable('tx_dlf_documents');
281
282
        $documents = [];
283
        $pageId = (int) $pageId;
284
        $result = $queryBuilder
285
            ->select('uid')
286
            ->from('tx_dlf_documents')
287
            ->where(
288
                $queryBuilder->expr()->eq(
289
                    'tx_dlf_documents.pid',
290
                    $queryBuilder->createNamedParameter($pageId, Connection::PARAM_INT)
291
                )
292
            )
293
            ->orderBy('tx_dlf_documents.uid', 'ASC')
294
            ->execute();
295
296
        while ($record = $result->fetch()) {
297
            $documents[] = $record['uid'];
298
        }
299
        return $documents;
300
    }
301
}
302