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 (#737)
by Alexander
02:59
created

CollectionController::injectDocumentRepository()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
4
 *
5
 * This file is part of the Kitodo and TYPO3 projects.
6
 *
7
 * @license GNU General Public License version 3 or later.
8
 * For the full copyright and license information, please read the
9
 * LICENSE.txt file that was distributed with this source code.
10
 */
11
12
namespace Kitodo\Dlf\Controller;
13
14
use Kitodo\Dlf\Common\DocumentList;
15
use Kitodo\Dlf\Common\Helper;
16
use Kitodo\Dlf\Common\Solr;
17
use Kitodo\Dlf\Domain\Model\Document;
18
use TYPO3\CMS\Core\Utility\GeneralUtility;
19
use TYPO3\CMS\Core\Utility\MathUtility;
20
use TYPO3\CMS\Frontend\Page\PageRepository;
21
use Kitodo\Dlf\Domain\Repository\CollectionRepository;
22
use Kitodo\Dlf\Domain\Repository\DocumentRepository;
23
24
class CollectionController extends AbstractController
25
{
26
    /**
27
     * This holds the hook objects
28
     *
29
     * @var array
30
     * @access protected
31
     */
32
    protected $hookObjects = [];
33
34
    protected $collectionRepository;
35
36
    /**
37
     * @param CollectionRepository $collectionRepository
38
     */
39
    public function injectCollectionRepository(CollectionRepository $collectionRepository)
40
    {
41
        $this->collectionRepository = $collectionRepository;
42
    }
43
44
    protected $documentRepository;
45
46
    /**
47
     * @param DocumentRepository $documentRepository
48
     */
49
    public function injectDocumentRepository(DocumentRepository $documentRepository)
50
    {
51
        $this->documentRepository = $documentRepository;
52
    }
53
54
    /**
55
     * The main method of the plugin
56
     *
57
     * @return void
58
     */
59
    public function mainAction()
60
    {
61
        // access to GET parameter tx_dlf_collection['collection']
62
        $requestData = $this->request->getArguments();
63
64
        $collection = $requestData['collection'];
65
66
        // Quit without doing anything if required configuration variables are not set.
67
        if (empty($this->settings['pages'])) {
68
            $this->logger->warning('Incomplete plugin configuration');
1 ignored issue
show
Bug introduced by
The method warning() does not exist on null. ( Ignorable by Annotation )

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

68
            $this->logger->/** @scrutinizer ignore-call */ 
69
                           warning('Incomplete plugin configuration');

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
        // Get hook objects.
72
        // TODO: $this->hookObjects = Helper::getHookObjects($this->scriptRelPath);
73
74
        if ($collection) {
75
            $this->showSingleCollection($collection);
76
        } else {
77
            $this->showCollectionList();
78
        }
79
80
        $this->view->assign('currentPageUid', $GLOBALS['TSFE']->id);
81
    }
82
83
    /**
84
     * Builds a collection list
85
     * @return void
86
     */
87
    protected function showCollectionList()
88
    {
89
90
        $result = $this->collectionRepository->getCollections($this->settings, $GLOBALS['TSFE']->fe_user->user['uid'], $GLOBALS['TSFE']->sys_language_uid);
91
        $count = $result['count'];
92
        $result = $result['result'];
93
94
        if ($count == 1 && empty($this->settings['dont_show_single'])) {
95
            $resArray = $result->fetch();
96
            $this->showSingleCollection(intval($resArray['uid']));
97
        }
98
        $solr = Solr::getInstance($this->settings['solrcore']);
99
        if (!$solr->ready) {
100
            $this->logger->error('Apache Solr not available');
101
            //return $content;
102
        }
103
        // We only care about the UID and partOf in the results and want them sorted
104
        $params['fields'] = 'uid,partof';
105
        $params['sort'] = ['uid' => 'asc'];
106
        $collections = [];
107
108
        // Get language overlay if on alterative website language.
109
        $pageRepository = GeneralUtility::makeInstance(PageRepository::class);
110
        while ($collectionData = $result->fetch()) {
111
            if ($collectionData['sys_language_uid'] != $GLOBALS['TSFE']->sys_language_content) {
112
                $collections[$collectionData['uid']] = $pageRepository->getRecordOverlay('tx_dlf_collections', $collectionData, $GLOBALS['TSFE']->sys_language_content, $GLOBALS['TSFE']->sys_language_contentOL);
113
                // keep the index_name of the default language
114
                $collections[$collectionData['uid']]['index_name'] = $collectionData['index_name'];
115
            } else {
116
                $collections[$collectionData['uid']] = $collectionData;
117
            }
118
        }
119
        // Sort collections according to flexform configuration
120
        if ($this->settings['collections']) {
121
            $sortedCollections = [];
122
            foreach (GeneralUtility::intExplode(',', $this->settings['collections']) as $uid) {
123
                $sortedCollections[$uid] = $collections[$uid];
124
            }
125
            $collections = $sortedCollections;
126
        }
127
128
        $processedCollections = [];
129
130
        // Process results.
131
        foreach ($collections as $collection) {
132
            $solr_query = '';
133
            if ($collection['index_query'] != '') {
134
                $solr_query .= '(' . $collection['index_query'] . ')';
135
            } else {
136
                $solr_query .= 'collection:("' . $collection['index_name'] . '")';
137
            }
138
            $partOfNothing = $solr->search_raw($solr_query . ' AND partof:0 AND toplevel:true', $params);
139
            $partOfSomething = $solr->search_raw($solr_query . ' AND NOT partof:0 AND toplevel:true', $params);
140
            // Titles are all documents that are "root" elements i.e. partof == 0
141
            $collection['titles'] = [];
142
            foreach ($partOfNothing as $doc) {
143
                $collection['titles'][$doc->uid] = $doc->uid;
144
            }
145
            // Volumes are documents that are both
146
            // a) "leaf" elements i.e. partof != 0
147
            // b) "root" elements that are not referenced by other documents ("root" elements that have no descendants)
148
            $collection['volumes'] = $collection['titles'];
149
            foreach ($partOfSomething as $doc) {
150
                $collection['volumes'][$doc->uid] = $doc->uid;
151
                // If a document is referenced via partof, it’s not a volume anymore.
152
                unset($collection['volumes'][$doc->partof]);
153
            }
154
155
            // Generate random but unique array key taking priority into account.
156
            do {
157
                $_key = ($collection['priority'] * 1000) + mt_rand(0, 1000);
158
            } while (!empty($processedCollections[$_key]));
159
160
            $collection['countTitles'] = count($collection['titles']);
161
            $collection['countVolumes'] = count($collection['volumes']);
162
163
            $processedCollections[$_key] = $collection;
164
        }
165
166
        // Randomize sorting?
167
        if (!empty($this->settings['randomize'])) {
168
            ksort($processedCollections, SORT_NUMERIC);
169
        }
170
171
        // TODO: Hook for getting custom collection hierarchies/subentries (requested by SBB).
172
        /*    foreach ($this->hookObjects as $hookObj) {
173
                if (method_exists($hookObj, 'showCollectionList_getCustomCollectionList')) {
174
                    $hookObj->showCollectionList_getCustomCollectionList($this, $this->settings['templateFile'], $content, $markerArray);
175
                }
176
            }
177
        */
178
179
        $this->view->assign('collections', $processedCollections);
180
    }
181
182
    /**
183
     * Builds a collection's list
184
     *
185
     * @access protected
186
     *
187
     * @param int $id: The collection's UID
188
     *
189
     * @return void
190
     */
191
    protected function showSingleCollection($id)
192
    {
193
        $collection = $this->collectionRepository->getSingleCollection($this->settings, $id, $GLOBALS['TSFE']->sys_language_uid);
194
195
        // Get language overlay if on alterative website language.
196
        $pageRepository = GeneralUtility::makeInstance(PageRepository::class);
197
        if ($resArray = $collection->fetch()) {
198
            if ($resArray['sys_language_uid'] != $GLOBALS['TSFE']->sys_language_content) {
199
                $collectionData = $pageRepository->getRecordOverlay('tx_dlf_collections', $resArray, $GLOBALS['TSFE']->sys_language_content, $GLOBALS['TSFE']->sys_language_contentOL);
200
                // keep the index_name of the default language
201
                $collectionData['index_name'] = $resArray['index_name'];
202
            } else {
203
                $collectionData = $resArray;
204
            }
205
        } else {
206
            $this->logger->warning('No collection with UID ' . $id . ' found.');
207
            return;
208
        }
209
        // Fetch corresponding document UIDs from Solr.
210
        if ($collectionData['index_search'] != '') {
211
            $solr_query = '(' . $collectionData['index_search'] . ')';
212
        } else {
213
            $solr_query = 'collection:("' . $collectionData['index_name'] . '") AND toplevel:true';
214
        }
215
        $solr = Solr::getInstance($this->settings['solrcore']);
216
        if (!$solr->ready) {
217
            $this->logger->error('Apache Solr not available');
218
            return;
219
        }
220
        $params['fields'] = 'uid';
221
        $params['sort'] = ['uid' => 'asc'];
222
        $solrResult = $solr->search_raw($solr_query, $params);
223
        // Initialize array
224
        $documentSet = [];
225
        foreach ($solrResult as $doc) {
226
            if ($doc->uid) {
227
                $documentSet[] = $doc->uid;
228
            }
229
        }
230
        $documentSet = array_unique($documentSet);
231
232
        $documents = $this->documentRepository->getDocumentsFromDocumentset($documentSet, $this->settings['pages']);
233
234
        $toplevel = [];
235
        $subparts = [];
236
        $listMetadata = [];
237
        // Process results.
238
        /** @var Document $document */
239
        foreach ($documents as $document) {
240
            if (empty($listMetadata)) {
241
                $listMetadata = [
242
                    'label' => htmlspecialchars($collectionData['label']),
243
                    'description' => $collectionData['description'],
244
                    'thumbnail' => htmlspecialchars($collectionData['thumbnail']),
245
                    'options' => [
246
                        'source' => 'collection',
247
                        'select' => $id,
248
                        'userid' => $collectionData['userid'],
249
                        'params' => ['filterquery' => [['query' => 'collection_faceting:("' . $collectionData['index_name'] . '")']]],
250
                        'core' => '',
251
                        'pid' => $this->settings['pages'],
252
                        'order' => 'title',
253
                        'order.asc' => true
254
                    ]
255
                ];
256
            }
257
            // Prepare document's metadata for sorting.
258
            $sorting = unserialize($document->getMetadataSorting());
259
            if (!empty($sorting['type']) && MathUtility::canBeInterpretedAsInteger($sorting['type'])) {
260
                $sorting['type'] = Helper::getIndexNameFromUid($sorting['type'], 'tx_dlf_structures', $this->settings['pages']);
261
            }
262
            if (!empty($sorting['owner']) && MathUtility::canBeInterpretedAsInteger($sorting['owner'])) {
263
                $sorting['owner'] = Helper::getIndexNameFromUid($sorting['owner'], 'tx_dlf_libraries', $this->settings['pages']);
264
            }
265
            if (!empty($sorting['collection']) && MathUtility::canBeInterpretedAsInteger($sorting['collection'])) {
266
                $sorting['collection'] = Helper::getIndexNameFromUid($sorting['collection'], 'tx_dlf_collections', $this->settings['pages']);
267
            }
268
            // Split toplevel documents from volumes.
269
            if ($document->getPartof() == 0) {
270
                $toplevel[$document->getUid()] = [
271
                    'u' => $document->getUid(),
272
                    'h' => '',
273
                    's' => $sorting,
274
                    'p' => []
275
                ];
276
            } else {
277
                // volume_sorting should be always set - but it's not a required field. We append the uid to the array key to make it always unique.
278
                $subparts[$document->getPartof()][$document->getVolumeSorting() . str_pad($document->getUid(), 9, '0', STR_PAD_LEFT)] = [
279
                    'u' => $document->getUid(),
280
                    'h' => '',
281
                    's' => $sorting,
282
                    'p' => []
283
                ];
284
            }
285
        }
286
287
        // Add volumes to the corresponding toplevel documents.
288
        foreach ($subparts as $partof => $parts) {
289
            ksort($parts);
290
            foreach ($parts as $part) {
291
                if (!empty($toplevel[$partof])) {
292
                    $toplevel[$partof]['p'][] = ['u' => $part['u']];
293
                } else {
294
                    $toplevel[$part['u']] = $part;
295
                }
296
            }
297
        }
298
        // Save list of documents.
299
        $list = GeneralUtility::makeInstance(DocumentList::class);
300
        $list->reset();
301
        $list->add(array_values($toplevel));
302
        $listMetadata['options']['numberOfToplevelHits'] = count($list);
303
        $list->metadata = $listMetadata;
304
        $list->sort('title');
305
        $list->save();
306
        // Clean output buffer.
307
        ob_end_clean();
308
309
        $uri = $this->uriBuilder
310
            ->reset()
311
            ->setTargetPageUid($this->settings['targetPid'])
312
            ->uriFor('main', [], 'ListView', 'dlf', 'ListView');
313
        $this->redirectToURI($uri);
314
    }
315
}
316