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:31
created

DocumentRepository::findDocumentsBySettings()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
c 0
b 0
f 0
nc 8
nop 1
dl 0
loc 21
rs 9.6111
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 TYPO3\CMS\Core\Database\ConnectionPool;
18
use TYPO3\CMS\Core\Database\Connection;
19
use TYPO3\CMS\Core\Utility\GeneralUtility;
20
use TYPO3\CMS\Core\Utility\MathUtility;
21
use TYPO3\CMS\Extbase\Persistence\QueryInterface;
22
23
class DocumentRepository extends \TYPO3\CMS\Extbase\Persistence\Repository
24
{
25
    /**
26
     * Find one document by given parameters
27
     *
28
     * GET parameters may be:
29
     *
30
     * - 'id': the uid of the document
31
     * - 'location': the URL of the location of the XML file
32
     * - 'recordId': the record_id of the document
33
     *
34
     * @param array $parameters
35
     *
36
     * @return \Kitodo\Dlf\Domain\Model\Document|null
37
     */
38
    public function findOneByParameters($parameters)
39
    {
40
        $doc = null;
41
        $document = null;
42
43
        if (isset($parameters['id']) && MathUtility::canBeInterpretedAsInteger($parameters['id'])) {
44
45
            $document = $this->findOneByIdAndSettings($parameters['id']);
46
47
        } else if (isset($parameters['recordId'])) {
48
49
            $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

49
            /** @scrutinizer ignore-call */ 
50
            $document = $this->findOneByRecordId($parameters['recordId']);
Loading history...
50
51
        } else if (isset($parameters['location']) && GeneralUtility::isValidUrl($parameters['location'])) {
52
53
            $doc = Doc::getInstance($parameters['location'], [], true);
54
55
            if ($doc->recordId) {
56
                $document = $this->findOneByRecordId($doc->recordId);
57
            }
58
59
            if ($document === null) {
60
                // create new (dummy) Document object
61
                $document = GeneralUtility::makeInstance(Document::class);
62
                $document->setLocation($parameters['location']);
63
            }
64
65
        }
66
67
        if ($document !== null && $doc === null) {
68
            $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

68
            $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...
69
        }
70
71
        if ($doc !== null) {
72
            $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

72
            $document->/** @scrutinizer ignore-call */ 
73
                       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...
73
        }
74
75
        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...
76
77
    }
78
79
80
    public function findByUidAndPartOf($uid, $partOf)
81
    {
82
        $query = $this->createQuery();
83
84
        $query->matching($query->equals('uid', $uid));
85
        $query->matching($query->equals('partof', $partOf));
86
87
        return $query->execute();
88
    }
89
90
    /**
91
     * Find the oldest document
92
     *
93
     * @return \Kitodo\Dlf\Domain\Model\Document|null
94
     */
95
    public function findOldestDocument()
96
    {
97
        $query = $this->createQuery();
98
99
        $query->setOrderings(['tstamp' => QueryInterface::ORDER_ASCENDING]);
100
        $query->setLimit(1);
101
102
        return $query->execute()->getFirst();
103
    }
104
105
    /**
106
     * @param int $partOf
107
     * @param string $structure
108
     * @return array|\TYPO3\CMS\Extbase\Persistence\QueryResultInterface
109
     */
110
    public function getChildrenOfYearAnchor($partOf, $structure)
111
    {
112
        $query = $this->createQuery();
113
114
        $query->matching($query->equals('structure', Helper::getUidFromIndexName($structure, 'tx_dlf_structures')));
115
        $query->matching($query->equals('partof', $partOf));
116
117
        $query->setOrderings([
118
            'mets_orderlabel' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING
119
        ]);
120
121
        return $query->execute();
122
    }
123
124
    /**
125
     * Finds all documents for the given settings
126
     *
127
     * @param int $uid
128
     * @param array $settings
129
     *
130
     * @return \Kitodo\Dlf\Domain\Model\Document|null
131
     */
132
    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

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

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