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

BaseCommand::saveToDatabase()   D

Complexity

Conditions 26
Paths 25

Size

Total Lines 97
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 26
eloc 57
c 1
b 0
f 0
nc 25
nop 1
dl 0
loc 97
rs 4.1666

How to fix   Long Method    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\Command;
14
15
use Kitodo\Dlf\Common\Helper;
16
use Kitodo\Dlf\Domain\Repository\CollectionRepository;
17
use Kitodo\Dlf\Domain\Repository\DocumentRepository;
18
use Kitodo\Dlf\Domain\Repository\LibraryRepository;
19
use Kitodo\Dlf\Domain\Model\Document;
20
use Kitodo\Dlf\Domain\Model\Library;
21
use Symfony\Component\Console\Command\Command;
22
use TYPO3\CMS\Core\Utility\GeneralUtility;
23
use TYPO3\CMS\Core\Utility\MathUtility;
24
use TYPO3\CMS\Core\Database\ConnectionPool;
25
use TYPO3\CMS\Core\Database\Connection;
26
use TYPO3\CMS\Extbase\Configuration\ConfigurationManager;
27
use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager;
28
29
/**
30
 * Base class for CLI Command classes.
31
 *
32
 * @author Beatrycze Volk <[email protected]>
33
 * @package TYPO3
34
 * @subpackage dlf
35
 * @access public
36
 */
37
class BaseCommand extends Command
38
{
39
    /**
40
     * @var CollectionRepository
41
     */
42
    protected $collectionRepository;
43
44
    /**
45
     * @var DocumentRepository
46
     */
47
    protected $documentRepository;
48
49
    /**
50
     * @var LibraryRepository
51
     */
52
    protected $libraryRepository;
53
54
    /**
55
     * @var int
56
     */
57
    protected $storagePid;
58
59
    /**
60
     * @var \Kitodo\Dlf\Domain\Model\Library
61
     */
62
    protected $owner;
63
64
    /**
65
     * Initialize the extbase repository based on the given storagePid.
66
     *
67
     * TYPO3 10+: Find a better solution e.g. based on Symfonie Dependancy Injection.
68
     *
69
     * @param string|string[]|bool|null $inputPid possible pid
70
     *
71
     * @return bool
72
     */
73
    protected function initializeRepositories($storagePid)
74
    {
75
        if (MathUtility::canBeInterpretedAsInteger($storagePid)) {
76
            $configurationManager = GeneralUtility::makeInstance(ConfigurationManager::class);
77
            $frameworkConfiguration = $configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
78
79
            $frameworkConfiguration['persistence']['storagePid'] = MathUtility::forceIntegerInRange((int) $storagePid, 0);
80
            $configurationManager->setConfiguration($frameworkConfiguration);
81
82
            $this->collectionRepository = GeneralUtility::makeInstance(CollectionRepository::class);
83
            $this->documentRepository = GeneralUtility::makeInstance(DocumentRepository::class);
84
            $this->libraryRepository = GeneralUtility::makeInstance(LibraryRepository::class);
85
        } else {
86
            return false;
87
        }
88
        $this->storagePid = MathUtility::forceIntegerInRange((int) $storagePid, 0);
89
90
        return true;
91
    }
92
93
    /**
94
     * Return matching uid of Solr core depending on the input value.
95
     *
96
     * @param array $solrCores array of the valid Solr cores
97
     * @param string|bool|null $inputSolrId possible uid or name of Solr core
98
     *
99
     * @return int matching uid of Solr core
100
     */
101
    protected function getSolrCoreUid(array $solrCores, $inputSolrId): int
102
    {
103
        if (MathUtility::canBeInterpretedAsInteger($inputSolrId)) {
104
            $solrCoreUid = MathUtility::forceIntegerInRange((int) $inputSolrId, 0);
105
        } else {
106
            $solrCoreUid = $solrCores[$inputSolrId];
107
        }
108
        return $solrCoreUid;
109
    }
110
111
    /**
112
     * Fetches all Solr cores on given page.
113
     *
114
     * @param int $pageId The UID of the Solr core or 0 to disable indexing
115
     *
116
     * @return array Array of valid Solr cores
117
     */
118
    protected function getSolrCores(int $pageId): array
119
    {
120
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
121
            ->getQueryBuilderForTable('tx_dlf_solrcores');
122
123
        $solrCores = [];
124
        $result = $queryBuilder
125
            ->select('uid', 'index_name')
126
            ->from('tx_dlf_solrcores')
127
            ->where(
128
                $queryBuilder->expr()->eq(
129
                    'pid',
130
                    $queryBuilder->createNamedParameter((int) $pageId, Connection::PARAM_INT)
131
                )
132
            )
133
            ->execute();
134
135
        while ($record = $result->fetch()) {
136
            $solrCores[$record['index_name']] = $record['uid'];
137
        }
138
139
        return $solrCores;
140
    }
141
142
    /**
143
     * Load XML file / IIIF resource from URL
144
     *
145
     * @access protected
146
     *
147
     * @param string $location: The URL of the file to load
148
     *
149
     * @return string|bool the found xml as string or false on failure
150
     */
151
    protected function loadLocation($location)
152
    {
153
        // Load XML / JSON-LD file.
154
        if (GeneralUtility::isValidUrl($location)) {
155
            // Load extension configuration
156
            // $extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
157
            // // Set user-agent to identify self when fetching XML / JSON-LD data.
158
            // if (!empty($extConf['useragent'])) {
159
            //     @ini_set('user_agent', $extConf['useragent']);
160
            // }
161
            $fileResource = GeneralUtility::getUrl($location);
162
            if ($fileResource !== false) {
163
                $xml = Helper::getXmlFileAsString($fileResource);
164
                if ($xml !== false) {
165
                    return $xml;
166
                }
167
            }
168
        } else {
169
            $this->logger->error('Invalid file location "' . $location . '" for document loading');
0 ignored issues
show
Bug Best Practice introduced by
The property logger does not exist on Kitodo\Dlf\Command\BaseCommand. Did you maybe forget to declare it?
Loading history...
170
        }
171
        return false;
172
    }
173
174
    /**
175
     * Update or insert document to database
176
     *
177
     * @param int|string $doc The document uid from DB OR the location of a mets document.
178
     *
179
     * @return bool true on success
180
     */
181
    protected function saveToDatabase(Document $document)
182
    {
183
        $success = false;
184
185
        $doc = $document->getDoc();
186
        if ($doc === null) {
187
            return $success;
188
        }
189
        $doc->cPid = $this->storagePid;
190
191
        $metadata = $doc->getTitledata($this->storagePid);
192
193
        // set title data
194
        $document->setTitle($metadata['title'][0] ? : '');
195
        $document->setTitleSorting($metadata['title_sorting'][0]);
196
        $document->setPlace(implode('; ', $metadata['place']));
197
        $document->setYear(implode('; ', $metadata['year']));
198
199
        // Remove appended "valueURI" from authors' names for storing in database.
200
        foreach ($metadata['author'] as $i => $author) {
201
            $splitName = explode(chr(31), $author);
202
            $metadata['author'][$i] = $splitName[0];
203
        }
204
        $document->setAuthor(implode('; ', $metadata['author']));
205
        $document->setThumbnail($doc->getThumbnail() ? : 'la');
0 ignored issues
show
Bug introduced by
The method getThumbnail() does not exist on Kitodo\Dlf\Common\Doc. Did you maybe mean _getThumbnail()? ( Ignorable by Annotation )

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

205
        $document->setThumbnail($doc->/** @scrutinizer ignore-call */ getThumbnail() ? : 'la');

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...
206
        $document->setMetsLabel($metadata['mets_label'][0] ? : '');
207
        $document->setMetsOrderlabel($metadata['mets_orderlabel'][0] ? : '');
208
209
        $document->setStructure(Helper::getUidFromIndexName($metadata['type'][0], 'tx_dlf_structures') ? : 0);
0 ignored issues
show
Bug introduced by
It seems like Kitodo\Dlf\Common\Helper...x_dlf_structures') ?: 0 can also be of type string; however, parameter $structure of Kitodo\Dlf\Domain\Model\Document::setStructure() does only seem to accept integer, 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

209
        $document->setStructure(/** @scrutinizer ignore-type */ Helper::getUidFromIndexName($metadata['type'][0], 'tx_dlf_structures') ? : 0);
Loading history...
210
211
        $collections = $this->collectionRepository->findCollectionsBySettings(['index_name' => $metadata['collection']]);
212
        if ($collections) {
0 ignored issues
show
introduced by
$collections is of type TYPO3\CMS\Extbase\Persistence\QueryResultInterface, thus it always evaluated to true.
Loading history...
213
            foreach ($collections as $collection) {
214
                $document->addCollection($collection);
215
            }
216
        }
217
218
        // set identifiers
219
        $document->setProdId($metadata['prod_id'][0] ? : '');
220
        $document->setOpacId($metadata['opac_id'][0] ? : '');
221
        $document->setUnionId($metadata['union_id'][0] ? : '');
222
223
        $document->setRecordId($metadata['record_id'][0] ? : ''); // (?) $doc->recordId
224
        $document->setUrn($metadata['urn'][0] ? : '');
225
        $document->setPurl($metadata['purl'][0] ? : '');
226
        $document->setDocumentFormat($metadata['document_format'][0] ? : '');
227
228
        // set access
229
        $document->setLicense($metadata['license'][0] ? : '');
230
        $document->setTerms($metadata['terms'][0] ? : '');
231
        $document->setRestrictions($metadata['restrictions'][0] ? : '');
232
        $document->setOutOfPrint($metadata['out_of_print'][0] ? : '');
233
        $document->setRightsInfo($metadata['rights_info'][0] ? : '');
234
        $document->setStatus(0);
235
236
        if ($this->owner) {
237
            // library / owner is set by parameter --> take it.
238
            $document->setOwner($this->owner);
239
        } else {
240
            // owner is not set set but found by metadata --> take it or take default library
241
            $owner = $metadata['owner'][0] ? : 'default';
242
            $library = $this->libraryRepository->findOneByIndexName($owner);
0 ignored issues
show
Bug introduced by
The method findOneByIndexName() does not exist on Kitodo\Dlf\Domain\Repository\LibraryRepository. 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

242
            /** @scrutinizer ignore-call */ 
243
            $library = $this->libraryRepository->findOneByIndexName($owner);
Loading history...
243
            if ($library) {
244
                $document->setOwner($library);
245
            } else {
246
                // create library
247
                $newLibrary = GeneralUtility::makeInstance(Library::class);
248
249
                $newLibrary->setLabel($owner);
250
                $newLibrary->setIndexName($owner);
251
                $this->libraryRepository->add($newLibrary);
252
                $document->setOwner($newLibrary);
253
            }
254
        }
255
256
        // to be still (re-) implemented
257
        // 'metadata' => serialize($listed),
258
        // 'metadata_sorting' => serialize($sortable),
259
        // 'partof' => $partof,
260
        // 'volume' => $metadata['volume'][0],
261
        // 'volume_sorting' => $metadata['volume_sorting'][0],
262
263
        $document->setMetadata('');
264
        $document->setMetadataSorting('');
265
266
        if ($document->getUid() === null) {
267
            // new document
268
            $this->documentRepository->add($document);
269
        } else {
270
            // update of existing document
271
            $this->documentRepository->update($document);
272
        }
273
274
        $persistenceManager = GeneralUtility::makeInstance(PersistenceManager::class);
275
        $persistenceManager->persistAll();
276
277
        return $success;
278
    }
279
280
}
281