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:49 queued 01:03
created

DocumentRepository::findOneByParameters()   B

Complexity

Conditions 11
Paths 28

Size

Total Lines 38
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 18
nc 28
nop 1
dl 0
loc 38
rs 7.3166
c 0
b 0
f 0

How to fix   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\Domain\Repository;
14
15
use Kitodo\Dlf\Common\Doc;
16
use Kitodo\Dlf\Common\Helper;
17
use Kitodo\Dlf\Domain\Model\Document;
18
use TYPO3\CMS\Core\Database\ConnectionPool;
19
use TYPO3\CMS\Core\Database\Connection;
20
use TYPO3\CMS\Core\Utility\GeneralUtility;
21
use TYPO3\CMS\Core\Utility\MathUtility;
22
use TYPO3\CMS\Extbase\Persistence\QueryInterface;
23
24
class DocumentRepository extends \TYPO3\CMS\Extbase\Persistence\Repository
25
{
26
    /**
27
     * Find one document by given parameters
28
     *
29
     * GET parameters may be:
30
     *
31
     * - 'id': the uid of the document
32
     * - 'location': the URL of the location of the XML file
33
     * - 'recordId': the record_id of the document
34
     *
35
     * @param array $parameters
36
     *
37
     * @return \Kitodo\Dlf\Domain\Model\Document|null
38
     */
39
    public function findOneByParameters($parameters)
40
    {
41
        $doc = null;
42
        $document = null;
43
44
        if (isset($parameters['id']) && MathUtility::canBeInterpretedAsInteger($parameters['id'])) {
45
46
            $document = $this->findOneByIdAndSettings($parameters['id']);
47
48
        } else if (isset($parameters['recordId'])) {
49
50
            $document = $this->findOneByRecordId($parameters['recordId']);
0 ignored issues
show
Bug introduced by
The method findOneByRecordId() does not exist on Kitodo\Dlf\Domain\Repository\DocumentRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

50
            /** @scrutinizer ignore-call */ 
51
            $document = $this->findOneByRecordId($parameters['recordId']);
Loading history...
51
52
        } else if (isset($parameters['location']) && GeneralUtility::isValidUrl($parameters['location'])) {
53
54
            $doc = Doc::getInstance($parameters['location'], [], true);
55
56
            if ($doc->recordId) {
57
                $document = $this->findOneByRecordId($doc->recordId);
58
            }
59
60
            if ($document === null) {
61
                // create new (dummy) Document object
62
                $document = GeneralUtility::makeInstance(Document::class);
63
                $document->setLocation($parameters['location']);
64
            }
65
66
        }
67
68
        if ($document !== null && $doc === null) {
69
            $doc = Doc::getInstance($document->getLocation(), [], true);
0 ignored issues
show
Bug introduced by
The method getLocation() does not exist on TYPO3\CMS\Extbase\Persistence\QueryResultInterface. ( Ignorable by Annotation )

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

69
            $doc = Doc::getInstance($document->/** @scrutinizer ignore-call */ getLocation(), [], true);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
70
        }
71
72
        if ($doc !== null) {
73
            $document->setDoc($doc);
0 ignored issues
show
Bug introduced by
The method setDoc() does not exist on TYPO3\CMS\Extbase\Persistence\QueryResultInterface. ( Ignorable by Annotation )

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

73
            $document->/** @scrutinizer ignore-call */ 
74
                       setDoc($doc);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
74
        }
75
76
        return $document;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $document also could return the type TYPO3\CMS\Extbase\Persis...y<mixed,object>|integer which is incompatible with the documented return type Kitodo\Dlf\Domain\Model\Document|null.
Loading history...
77
78
    }
79
80
81
    public function findByUidAndPartOf($uid, $partOf)
82
    {
83
        $query = $this->createQuery();
84
85
        $query->matching($query->equals('uid', $uid));
86
        $query->matching($query->equals('partof', $partOf));
87
88
        return $query->execute();
89
    }
90
91
    /**
92
     * Find the oldest document
93
     *
94
     * @return \Kitodo\Dlf\Domain\Model\Document|null
95
     */
96
    public function findOldestDocument()
97
    {
98
        $query = $this->createQuery();
99
100
        $query->setOrderings(['tstamp' => QueryInterface::ORDER_ASCENDING]);
101
        $query->setLimit(1);
102
103
        return $query->execute()->getFirst();
104
    }
105
106
    /**
107
     * @param int $partOf
108
     * @param string $structure
109
     * @return array|\TYPO3\CMS\Extbase\Persistence\QueryResultInterface
110
     */
111
    public function getChildrenOfYearAnchor($partOf, $structure)
112
    {
113
        $query = $this->createQuery();
114
115
        $query->matching($query->equals('structure', Helper::getUidFromIndexName($structure, 'tx_dlf_structures')));
116
        $query->matching($query->equals('partof', $partOf));
117
118
        $query->setOrderings([
119
            'mets_orderlabel' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING
120
        ]);
121
122
        return $query->execute();
123
    }
124
125
    /**
126
     * Finds all documents for the given settings
127
     *
128
     * @param int $uid
129
     * @param array $settings
130
     *
131
     * @return \Kitodo\Dlf\Domain\Model\Document|null
132
     */
133
    public function findOneByIdAndSettings($uid, $settings = [])
0 ignored issues
show
Unused Code introduced by
The parameter $settings is not used and could be removed. ( Ignorable by Annotation )

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

133
    public function findOneByIdAndSettings($uid, /** @scrutinizer ignore-unused */ $settings = [])

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
134
    {
135
        $settings = ['documentSets' => $uid];
136
137
        return $this->findDocumentsBySettings($settings)->getFirst();
138
    }
139
140
    /**
141
     * Finds all documents for the given settings
142
     *
143
     * @param array $settings
144
     *
145
     * @return array|\TYPO3\CMS\Extbase\Persistence\QueryResultInterface
146
     */
147
    public function findDocumentsBySettings($settings = [])
148
    {
149
        $query = $this->createQuery();
150
151
        $constraints = [];
152
153
        if ($settings['documentSets']) {
154
            $constraints[] = $query->in('uid', GeneralUtility::intExplode(',', $settings['documentSets']));
155
        }
156
157
        if (isset($settings['excludeOther']) && (int) $settings['excludeOther'] === 0) {
158
            $query->getQuerySettings()->setRespectStoragePage(false);
159
        }
160
161
        if (count($constraints)) {
162
            $query->matching(
163
                $query->logicalAnd($constraints)
164
            );
165
        }
166
167
        return $query->execute();
168
    }
169
170
    /**
171
     * Finds all documents for the given collections
172
     *
173
     * @param array $collections
174
     * @param int $limit
175
     *
176
     * @return array|\TYPO3\CMS\Extbase\Persistence\QueryResultInterface
177
     */
178
    public function findAllByCollectionsLimited($collections, $limit = 50)
179
    {
180
        $query = $this->createQuery();
181
182
        // order by start_date -> start_time...
183
        $query->setOrderings(
184
            ['tstamp' => QueryInterface::ORDER_DESCENDING]
185
        );
186
187
        $constraints = [];
188
        if ($collections) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $collections of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
189
            $constraints[] = $query->in('collections.uid', $collections);
190
        }
191
192
        if (count($constraints)) {
193
            $query->matching(
194
                $query->logicalAnd($constraints)
195
            );
196
        }
197
198
        if ($limit > 0) {
199
            $query->setLimit((int) $limit);
200
        }
201
202
        return $query->execute();
203
    }
204
205
    /**
206
     * Find all the titles
207
     *
208
     * documents with partof == 0
209
     *
210
     * @param array $settings
211
     *
212
     * @return array|\TYPO3\CMS\Extbase\Persistence\QueryResultInterface
213
     */
214
    public function findAllTitles($settings = [])
215
    {
216
        $query = $this->createQuery();
217
218
        $constraints = [];
219
        $constraints[] = $query->equals('partof', 0);
220
221
        if ($settings['collections']) {
222
            $constraints[] = $query->in('collections.uid', GeneralUtility::intExplode(',', $settings['collections']));
223
        }
224
225
        if (count($constraints)) {
226
            $query->matching(
227
                $query->logicalAnd($constraints)
228
            );
229
        }
230
231
        return $query->execute();
232
    }
233
234
    /**
235
     * Count the titles
236
     *
237
     * documents with partof == 0
238
     *
239
     * @param array $settings
240
     *
241
     * @return int
242
     */
243
    public function countAllTitles($settings = [])
244
    {
245
        return $this->findAllTitles($settings)->count();
246
    }
247
248
    /**
249
     * Count the volumes
250
     *
251
     * documents with partof != 0
252
     *
253
     * @param array $settings
254
     *
255
     * @return int
256
     */
257
    public function countAllVolumes($settings = [])
258
    {
259
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
260
            ->getQueryBuilderForTable('tx_dlf_documents');
261
        $subQueryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
262
            ->getQueryBuilderForTable('tx_dlf_documents');
263
264
        $subQuery = $subQueryBuilder
265
            ->select('tx_dlf_documents.partof')
266
            ->from('tx_dlf_documents')
267
            ->where(
268
                $subQueryBuilder->expr()->neq('tx_dlf_documents.partof', 0)
269
            )
270
            ->groupBy('tx_dlf_documents.partof')
271
            ->getSQL();
272
273
        $countVolumes = $queryBuilder
274
            ->count('tx_dlf_documents.uid')
275
            ->from('tx_dlf_documents')
276
            ->where(
277
                $queryBuilder->expr()->eq('tx_dlf_documents.pid', intval($settings['pages'])),
278
                $queryBuilder->expr()->notIn('tx_dlf_documents.uid', $subQuery)
279
            )
280
            ->execute()
281
            ->fetchColumn(0);
282
283
        return $countVolumes;
284
    }
285
286
    public function getStatisticsForSelectedCollection($settings)
287
    {
288
        // Include only selected collections.
289
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
290
            ->getQueryBuilderForTable('tx_dlf_documents');
291
292
        $countTitles = $queryBuilder
293
            ->count('tx_dlf_documents.uid')
294
            ->from('tx_dlf_documents')
295
            ->innerJoin(
296
                'tx_dlf_documents',
297
                'tx_dlf_relations',
298
                'tx_dlf_relations_joins',
299
                $queryBuilder->expr()->eq(
300
                    'tx_dlf_relations_joins.uid_local',
301
                    'tx_dlf_documents.uid'
302
                )
303
            )
304
            ->innerJoin(
305
                'tx_dlf_relations_joins',
306
                'tx_dlf_collections',
307
                'tx_dlf_collections_join',
308
                $queryBuilder->expr()->eq(
309
                    'tx_dlf_relations_joins.uid_foreign',
310
                    'tx_dlf_collections_join.uid'
311
                )
312
            )
313
            ->where(
314
                $queryBuilder->expr()->eq('tx_dlf_documents.pid', intval($settings['pages'])),
315
                $queryBuilder->expr()->eq('tx_dlf_collections_join.pid', intval($settings['pages'])),
316
                $queryBuilder->expr()->eq('tx_dlf_documents.partof', 0),
317
                $queryBuilder->expr()->in('tx_dlf_collections_join.uid',
318
                    $queryBuilder->createNamedParameter(GeneralUtility::intExplode(',',
319
                        $settings['collections']), Connection::PARAM_INT_ARRAY)),
320
                $queryBuilder->expr()->eq('tx_dlf_relations_joins.ident',
321
                    $queryBuilder->createNamedParameter('docs_colls'))
322
            )
323
            ->execute()
324
            ->fetchColumn(0);
325
326
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
327
            ->getQueryBuilderForTable('tx_dlf_documents');
328
        $subQueryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
329
            ->getQueryBuilderForTable('tx_dlf_documents');
330
331
        $subQuery = $subQueryBuilder
332
            ->select('tx_dlf_documents.partof')
333
            ->from('tx_dlf_documents')
334
            ->where(
335
                $subQueryBuilder->expr()->neq('tx_dlf_documents.partof', 0)
336
            )
337
            ->groupBy('tx_dlf_documents.partof')
338
            ->getSQL();
339
340
        $countVolumes = $queryBuilder
341
            ->count('tx_dlf_documents.uid')
342
            ->from('tx_dlf_documents')
343
            ->innerJoin(
344
                'tx_dlf_documents',
345
                'tx_dlf_relations',
346
                'tx_dlf_relations_joins',
347
                $queryBuilder->expr()->eq(
348
                    'tx_dlf_relations_joins.uid_local',
349
                    'tx_dlf_documents.uid'
350
                )
351
            )
352
            ->innerJoin(
353
                'tx_dlf_relations_joins',
354
                'tx_dlf_collections',
355
                'tx_dlf_collections_join',
356
                $queryBuilder->expr()->eq(
357
                    'tx_dlf_relations_joins.uid_foreign',
358
                    'tx_dlf_collections_join.uid'
359
                )
360
            )
361
            ->where(
362
                $queryBuilder->expr()->eq('tx_dlf_documents.pid', intval($settings['pages'])),
363
                $queryBuilder->expr()->eq('tx_dlf_collections_join.pid', intval($settings['pages'])),
364
                $queryBuilder->expr()->notIn('tx_dlf_documents.uid', $subQuery),
365
                $queryBuilder->expr()->in('tx_dlf_collections_join.uid',
366
                    $queryBuilder->createNamedParameter(GeneralUtility::intExplode(',',
367
                        $settings['collections']), Connection::PARAM_INT_ARRAY)),
368
                $queryBuilder->expr()->eq('tx_dlf_relations_joins.ident',
369
                    $queryBuilder->createNamedParameter('docs_colls'))
370
            )
371
            ->execute()
372
            ->fetchColumn(0);
373
374
        return ['titles' => $countTitles, 'volumes' => $countVolumes];
375
    }
376
377
    public function getTableOfContentsFromDb($uid, $pid, $settings)
378
    {
379
        // Build table of contents from database.
380
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
381
            ->getQueryBuilderForTable('tx_dlf_documents');
382
383
        $excludeOtherWhere = '';
384
        if ($settings['excludeOther']) {
385
            $excludeOtherWhere = 'tx_dlf_documents.pid=' . intval($settings['pages']);
386
        }
387
        // Check if there are any metadata to suggest.
388
        $result = $queryBuilder
389
            ->select(
390
                'tx_dlf_documents.uid AS uid',
391
                'tx_dlf_documents.title AS title',
392
                'tx_dlf_documents.volume AS volume',
393
                'tx_dlf_documents.mets_label AS mets_label',
394
                'tx_dlf_documents.mets_orderlabel AS mets_orderlabel',
395
                'tx_dlf_structures_join.index_name AS type'
396
            )
397
            ->innerJoin(
398
                'tx_dlf_documents',
399
                'tx_dlf_structures',
400
                'tx_dlf_structures_join',
401
                $queryBuilder->expr()->eq(
402
                    'tx_dlf_structures_join.uid',
403
                    'tx_dlf_documents.structure'
404
                )
405
            )
406
            ->from('tx_dlf_documents')
407
            ->where(
408
                $queryBuilder->expr()->eq('tx_dlf_documents.partof', intval($uid)),
409
                $queryBuilder->expr()->eq('tx_dlf_structures_join.pid', intval($pid)),
410
                $excludeOtherWhere
411
            )
412
            ->addOrderBy('tx_dlf_documents.volume_sorting')
413
            ->addOrderBy('tx_dlf_documents.mets_orderlabel')
414
            ->execute();
415
        return $result;
416
    }
417
418
    /**
419
     * Find one document by given settings and identifier
420
     *
421
     * @param array $settings
422
     * @param array $parameters
423
     *
424
     * @return array The found document object
425
     */
426
    public function getOaiRecord($settings, $parameters)
427
    {
428
        $where = '';
429
430
        if (!$settings['show_userdefined']) {
431
            $where .= 'AND tx_dlf_collections.fe_cruser_id=0 ';
432
        }
433
434
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)
435
            ->getConnectionForTable('tx_dlf_documents');
436
437
        $sql = 'SELECT `tx_dlf_documents`.*, GROUP_CONCAT(DISTINCT `tx_dlf_collections`.`oai_name` ORDER BY `tx_dlf_collections`.`oai_name` SEPARATOR " ") AS `collections` ' .
438
            'FROM `tx_dlf_documents` ' .
439
            'INNER JOIN `tx_dlf_relations` ON `tx_dlf_relations`.`uid_local` = `tx_dlf_documents`.`uid` ' .
440
            'INNER JOIN `tx_dlf_collections` ON `tx_dlf_collections`.`uid` = `tx_dlf_relations`.`uid_foreign` ' .
441
            'WHERE `tx_dlf_documents`.`record_id` = ? ' .
442
            'AND `tx_dlf_relations`.`ident`="docs_colls" ' .
443
            $where;
444
445
        $values = [
446
            $parameters['identifier']
447
        ];
448
449
        $types = [
450
            Connection::PARAM_STR
451
        ];
452
453
        // Create a prepared statement for the passed SQL query, bind the given params with their binding types and execute the query
454
        $statement = $connection->executeQuery($sql, $values, $types);
455
456
        return $statement->fetch();
457
    }
458
459
    /**
460
     * Finds all documents for the given settings
461
     *
462
     * @param array $settings
463
     * @param array $documentsToProcess
464
     *
465
     * @return array The found document objects
466
     */
467
    public function getOaiDocumentList($settings, $documentsToProcess)
0 ignored issues
show
Unused Code introduced by
The parameter $settings is not used and could be removed. ( Ignorable by Annotation )

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

467
    public function getOaiDocumentList(/** @scrutinizer ignore-unused */ $settings, $documentsToProcess)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
468
    {
469
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)
470
            ->getConnectionForTable('tx_dlf_documents');
471
472
        $sql = 'SELECT `tx_dlf_documents`.*, GROUP_CONCAT(DISTINCT `tx_dlf_collections`.`oai_name` ORDER BY `tx_dlf_collections`.`oai_name` SEPARATOR " ") AS `collections` ' .
473
            'FROM `tx_dlf_documents` ' .
474
            'INNER JOIN `tx_dlf_relations` ON `tx_dlf_relations`.`uid_local` = `tx_dlf_documents`.`uid` ' .
475
            'INNER JOIN `tx_dlf_collections` ON `tx_dlf_collections`.`uid` = `tx_dlf_relations`.`uid_foreign` ' .
476
            'WHERE `tx_dlf_documents`.`uid` IN ( ? ) ' .
477
            'AND `tx_dlf_relations`.`ident`="docs_colls" ' .
478
            'AND ' . Helper::whereExpression('tx_dlf_collections') . ' ' .
479
            'GROUP BY `tx_dlf_documents`.`uid` ';
480
481
        $values = [
482
            $documentsToProcess,
483
        ];
484
485
        $types = [
486
            Connection::PARAM_INT_ARRAY,
487
        ];
488
489
        // Create a prepared statement for the passed SQL query, bind the given params with their binding types and execute the query
490
        $documents = $connection->executeQuery($sql, $values, $types);
491
492
        return $documents;
493
    }
494
495
}
496