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
created

BaseCommand::loadLocation()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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

219
        $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...
220
        $document->setMetsLabel($metadata['mets_label'][0] ? : '');
221
        $document->setMetsOrderlabel($metadata['mets_orderlabel'][0] ? : '');
222
223
        $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

223
        $document->setStructure(/** @scrutinizer ignore-type */ Helper::getUidFromIndexName($metadata['type'][0], 'tx_dlf_structures') ? : 0);
Loading history...
224
225
        $collections = $this->collectionRepository->findCollectionsBySettings(['index_name' => $metadata['collection']]);
226
        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...
227
            foreach ($collections as $collection) {
228
                $document->addCollection($collection);
229
            }
230
        }
231
232
        // set identifiers
233
        $document->setProdId($metadata['prod_id'][0] ? : '');
234
        $document->setOpacId($metadata['opac_id'][0] ? : '');
235
        $document->setUnionId($metadata['union_id'][0] ? : '');
236
237
        $document->setRecordId($metadata['record_id'][0] ? : ''); // (?) $doc->recordId
238
        $document->setUrn($metadata['urn'][0] ? : '');
239
        $document->setPurl($metadata['purl'][0] ? : '');
240
        $document->setDocumentFormat($metadata['document_format'][0] ? : '');
241
242
        // set access
243
        $document->setLicense($metadata['license'][0] ? : '');
244
        $document->setTerms($metadata['terms'][0] ? : '');
245
        $document->setRestrictions($metadata['restrictions'][0] ? : '');
246
        $document->setOutOfPrint($metadata['out_of_print'][0] ? : '');
247
        $document->setRightsInfo($metadata['rights_info'][0] ? : '');
248
        $document->setStatus(0);
249
250
        if ($this->owner) {
251
            // library / owner is set by parameter --> take it.
252
            $document->setOwner($this->owner);
253
        } else {
254
            // owner is not set set but found by metadata --> take it or take default library
255
            $owner = $metadata['owner'][0] ? : 'default';
256
            $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

256
            /** @scrutinizer ignore-call */ 
257
            $library = $this->libraryRepository->findOneByIndexName($owner);
Loading history...
257
            if ($library) {
258
                $document->setOwner($library);
259
            } else {
260
                // create library
261
                $newLibrary = $this->objectManager->get(Library::class);
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Extbase\Object\ObjectManager::get() has been deprecated: since TYPO3 10.4, will be removed in version 12.0 ( Ignorable by Annotation )

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

261
                $newLibrary = /** @scrutinizer ignore-deprecated */ $this->objectManager->get(Library::class);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
262
263
                $newLibrary->setLabel($owner);
264
                $newLibrary->setIndexName($owner);
265
                $this->libraryRepository->add($newLibrary);
266
                $document->setOwner($newLibrary);
267
            }
268
        }
269
270
        // to be still (re-) implemented
271
        // 'metadata' => serialize($listed),
272
        // 'metadata_sorting' => serialize($sortable),
273
        // 'partof' => $partof,
274
        // 'volume' => $metadata['volume'][0],
275
        // 'volume_sorting' => $metadata['volume_sorting'][0],
276
277
        $document->setMetadata('');
278
        $document->setMetadataSorting('');
279
280
        if ($document->getUid() === null) {
281
            // new document
282
            $this->documentRepository->add($document);
283
        } else {
284
            // update of existing document
285
            $this->documentRepository->update($document);
286
        }
287
288
        $persistenceManager = $this->objectManager->get(PersistenceManager::class);
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Extbase\Object\ObjectManager::get() has been deprecated: since TYPO3 10.4, will be removed in version 12.0 ( Ignorable by Annotation )

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

288
        $persistenceManager = /** @scrutinizer ignore-deprecated */ $this->objectManager->get(PersistenceManager::class);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
289
        $persistenceManager->persistAll();
290
291
        return $success;
292
    }
293
294
}
295