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 — master (#837)
by Beatrycze
04:04
created

MetsDocument::_getThumbnail()   C

Complexity

Conditions 14
Paths 29

Size

Total Lines 74
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 50
c 1
b 0
f 0
dl 0
loc 74
rs 6.2666
cc 14
nc 29
nop 1

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\Common;
14
15
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
16
use TYPO3\CMS\Core\Database\ConnectionPool;
17
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
18
use TYPO3\CMS\Core\Utility\GeneralUtility;
19
use Ubl\Iiif\Tools\IiifHelper;
20
use Ubl\Iiif\Services\AbstractImageService;
21
use TYPO3\CMS\Core\Log\LogManager;
22
23
/**
24
 * MetsDocument class for the 'dlf' extension.
25
 *
26
 * @author Sebastian Meyer <[email protected]>
27
 * @author Henrik Lochmann <[email protected]>
28
 * @package TYPO3
29
 * @subpackage dlf
30
 * @access public
31
 * @property int $cPid This holds the PID for the configuration
32
 * @property-read array $dmdSec This holds the XML file's dmdSec parts with their IDs as array key
33
 * @property-read array $fileGrps This holds the file ID -> USE concordance
34
 * @property-read bool $hasFulltext Are there any fulltext files available?
35
 * @property-read array $metadataArray This holds the documents' parsed metadata array
36
 * @property-read \SimpleXMLElement $mets This holds the XML file's METS part as \SimpleXMLElement object
37
 * @property-read int $numPages The holds the total number of pages
38
 * @property-read int $parentId This holds the UID of the parent document or zero if not multi-volumed
39
 * @property-read array $physicalStructure This holds the physical structure
40
 * @property-read array $physicalStructureInfo This holds the physical structure metadata
41
 * @property-read int $pid This holds the PID of the document or zero if not in database
42
 * @property-read bool $ready Is the document instantiated successfully?
43
 * @property-read string $recordId The METS file's / IIIF manifest's record identifier
44
 * @property-read int $rootId This holds the UID of the root document or zero if not multi-volumed
45
 * @property-read array $smLinks This holds the smLinks between logical and physical structMap
46
 * @property-read array $tableOfContents This holds the logical structure
47
 * @property-read string $thumbnail This holds the document's thumbnail location
48
 * @property-read string $toplevelId This holds the toplevel structure's @ID (METS) or the manifest's @id (IIIF)
49
 */
50
final class MetsDocument extends Doc
51
{
52
    /**
53
     * This holds the whole XML file as string for serialization purposes
54
     * @see __sleep() / __wakeup()
55
     *
56
     * @var string
57
     * @access protected
58
     */
59
    protected $asXML = '';
60
61
    /**
62
     * This holds the XML file's dmdSec parts with their IDs as array key
63
     *
64
     * @var array
65
     * @access protected
66
     */
67
    protected $dmdSec = [];
68
69
    /**
70
     * Are the METS file's dmdSecs loaded?
71
     * @see $dmdSec
72
     *
73
     * @var bool
74
     * @access protected
75
     */
76
    protected $dmdSecLoaded = false;
77
78
    /**
79
     * The extension key
80
     *
81
     * @var	string
82
     * @access public
83
     */
84
    public static $extKey = 'dlf';
85
86
    /**
87
     * This holds the file ID -> USE concordance
88
     * @see _getFileGrps()
89
     *
90
     * @var array
91
     * @access protected
92
     */
93
    protected $fileGrps = [];
94
95
    /**
96
     * Are the image file groups loaded?
97
     * @see $fileGrps
98
     *
99
     * @var bool
100
     * @access protected
101
     */
102
    protected $fileGrpsLoaded = false;
103
104
    /**
105
     * This holds the XML file's METS part as \SimpleXMLElement object
106
     *
107
     * @var \SimpleXMLElement
108
     * @access protected
109
     */
110
    protected $mets;
111
112
    /**
113
     * This holds the whole XML file as \SimpleXMLElement object
114
     *
115
     * @var \SimpleXMLElement
116
     * @access protected
117
     */
118
    protected $xml;
119
120
    /**
121
     * This adds metadata from METS structural map to metadata array.
122
     *
123
     * @access	public
124
     *
125
     * @param	array	&$metadata: The metadata array to extend
126
     * @param	string	$id: The "@ID" attribute of the logical structure node
127
     *
128
     * @return  void
129
     */
130
    public function addMetadataFromMets(&$metadata, $id)
131
    {
132
        $details = $this->getLogicalStructure($id);
133
        if (!empty($details)) {
134
            $metadata['mets_order'][0] = $details['order'];
135
            $metadata['mets_label'][0] = $details['label'];
136
            $metadata['mets_orderlabel'][0] = $details['orderlabel'];
137
        }
138
    }
139
140
    /**
141
     *
142
     * {@inheritDoc}
143
     * @see \Kitodo\Dlf\Common\Doc::establishRecordId()
144
     */
145
    protected function establishRecordId($pid)
146
    {
147
        // Check for METS object @ID.
148
        if (!empty($this->mets['OBJID'])) {
149
            $this->recordId = (string) $this->mets['OBJID'];
150
        }
151
        // Get hook objects.
152
        $hookObjects = Helper::getHookObjects('Classes/Common/MetsDocument.php');
153
        // Apply hooks.
154
        foreach ($hookObjects as $hookObj) {
155
            if (method_exists($hookObj, 'construct_postProcessRecordId')) {
156
                $hookObj->construct_postProcessRecordId($this->xml, $this->recordId);
157
            }
158
        }
159
    }
160
161
    /**
162
     *
163
     * {@inheritDoc}
164
     * @see \Kitodo\Dlf\Common\Doc::getDownloadLocation()
165
     */
166
    public function getDownloadLocation($id)
167
    {
168
        $fileMimeType = $this->getFileMimeType($id);
169
        $fileLocation = $this->getFileLocation($id);
170
        if ($fileMimeType === 'application/vnd.kitodo.iiif') {
171
            $fileLocation = (strrpos($fileLocation, 'info.json') === strlen($fileLocation) - 9) ? $fileLocation : (strrpos($fileLocation, '/') === strlen($fileLocation) ? $fileLocation . 'info.json' : $fileLocation . '/info.json');
172
            $conf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
173
            IiifHelper::setUrlReader(IiifUrlReader::getInstance());
174
            IiifHelper::setMaxThumbnailHeight($conf['iiifThumbnailHeight']);
175
            IiifHelper::setMaxThumbnailWidth($conf['iiifThumbnailWidth']);
176
            $service = IiifHelper::loadIiifResource($fileLocation);
177
            if ($service !== null && $service instanceof AbstractImageService) {
178
                return $service->getImageUrl();
179
            }
180
        } elseif ($fileMimeType === 'application/vnd.netfpx') {
181
            $baseURL = $fileLocation . (strpos($fileLocation, '?') === false ? '?' : '');
182
            // TODO CVT is an optional IIP server capability; in theory, capabilities should be determined in the object request with '&obj=IIP-server'
183
            return $baseURL . '&CVT=jpeg';
184
        }
185
        return $fileLocation;
186
    }
187
188
    /**
189
     * {@inheritDoc}
190
     * @see \Kitodo\Dlf\Common\Doc::getFileLocation()
191
     */
192
    public function getFileLocation($id)
193
    {
194
        $location = $this->mets->xpath('./mets:fileSec/mets:fileGrp/mets:file[@ID="' . $id . '"]/mets:FLocat[@LOCTYPE="URL"]');
195
        if (
196
            !empty($id)
197
            && !empty($location)
198
        ) {
199
            return (string) $location[0]->attributes('http://www.w3.org/1999/xlink')->href;
200
        } else {
201
            $this->logger->warning('There is no file node with @ID "' . $id . '"');
202
            return '';
203
        }
204
    }
205
206
    /**
207
     * {@inheritDoc}
208
     * @see \Kitodo\Dlf\Common\Doc::getFileMimeType()
209
     */
210
    public function getFileMimeType($id)
211
    {
212
        $mimetype = $this->mets->xpath('./mets:fileSec/mets:fileGrp/mets:file[@ID="' . $id . '"]/@MIMETYPE');
213
        if (
214
            !empty($id)
215
            && !empty($mimetype)
216
        ) {
217
            return (string) $mimetype[0];
218
        } else {
219
            $this->logger->warning('There is no file node with @ID "' . $id . '" or no MIME type specified');
220
            return '';
221
        }
222
    }
223
224
    /**
225
     * {@inheritDoc}
226
     * @see \Kitodo\Dlf\Common\Doc::getLogicalStructure()
227
     */
228
    public function getLogicalStructure($id, $recursive = false)
229
    {
230
        $details = [];
231
        // Is the requested logical unit already loaded?
232
        if (
233
            !$recursive
234
            && !empty($this->logicalUnits[$id])
235
        ) {
236
            // Yes. Return it.
237
            return $this->logicalUnits[$id];
238
        } elseif (!empty($id)) {
239
            // Get specified logical unit.
240
            $divs = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@ID="' . $id . '"]');
241
        } else {
242
            // Get all logical units at top level.
243
            $divs = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]/mets:div');
244
        }
245
        if (!empty($divs)) {
246
            if (!$recursive) {
247
                // Get the details for the first xpath hit.
248
                $details = $this->getLogicalStructureInfo($divs[0]);
249
            } else {
250
                // Walk the logical structure recursively and fill the whole table of contents.
251
                foreach ($divs as $div) {
252
                    $this->tableOfContents[] = $this->getLogicalStructureInfo($div, $recursive);
253
                }
254
            }
255
        }
256
        return $details;
257
    }
258
259
    /**
260
     * This gets details about a logical structure element
261
     *
262
     * @access protected
263
     *
264
     * @param \SimpleXMLElement $structure: The logical structure node
265
     * @param bool $recursive: Whether to include the child elements
266
     *
267
     * @return array Array of the element's id, label, type and physical page indexes/mptr link
268
     */
269
    protected function getLogicalStructureInfo(\SimpleXMLElement $structure, $recursive = false)
270
    {
271
        // Get attributes.
272
        foreach ($structure->attributes() as $attribute => $value) {
273
            $attributes[$attribute] = (string) $value;
274
        }
275
        // Load plugin configuration.
276
        $extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
277
        // Extract identity information.
278
        $details = [];
279
        $details['id'] = $attributes['ID'];
280
        $details['dmdId'] = (isset($attributes['DMDID']) ? $attributes['DMDID'] : '');
281
        $details['order'] = (isset($attributes['ORDER']) ? $attributes['ORDER'] : '');
282
        $details['label'] = (isset($attributes['LABEL']) ? $attributes['LABEL'] : '');
283
        $details['orderlabel'] = (isset($attributes['ORDERLABEL']) ? $attributes['ORDERLABEL'] : '');
284
        $details['contentIds'] = (isset($attributes['CONTENTIDS']) ? $attributes['CONTENTIDS'] : '');
285
        $details['volume'] = '';
286
        // Set volume information only if no label is set and this is the toplevel structure element.
287
        if (
288
            empty($details['label'])
289
            && $details['id'] == $this->_getToplevelId()
290
        ) {
291
            $metadata = $this->getMetadata($details['id']);
292
            if (!empty($metadata['volume'][0])) {
293
                $details['volume'] = $metadata['volume'][0];
294
            }
295
        }
296
        $details['pagination'] = '';
297
        $details['type'] = $attributes['TYPE'];
298
        $details = $this->getLogicalStructureFor3D($details);
299
        $details['thumbnailId'] = '';
300
        // Load smLinks.
301
        $this->_getSmLinks();
302
        // Load physical structure.
303
        $this->_getPhysicalStructure();
304
        // Get the physical page or external file this structure element is pointing at.
305
        $details['points'] = '';
306
        // Is there a mptr node?
307
        if (count($structure->children('http://www.loc.gov/METS/')->mptr)) {
308
            // Yes. Get the file reference.
309
            $details['points'] = (string) $structure->children('http://www.loc.gov/METS/')->mptr[0]->attributes('http://www.w3.org/1999/xlink')->href;
310
        } elseif (
311
            !empty($this->physicalStructure)
312
            && array_key_exists($details['id'], $this->smLinks['l2p'])
313
        ) {
314
            // Link logical structure to the first corresponding physical page/track.
315
            $details['points'] = max(intval(array_search($this->smLinks['l2p'][$details['id']][0], $this->physicalStructure, true)), 1);
316
            $fileGrpsThumb = GeneralUtility::trimExplode(',', $extConf['fileGrpThumbs']);
317
            while ($fileGrpThumb = array_shift($fileGrpsThumb)) {
318
                if (!empty($this->physicalStructureInfo[$this->smLinks['l2p'][$details['id']][0]]['files'][$fileGrpThumb])) {
319
                    $details['thumbnailId'] = $this->physicalStructureInfo[$this->smLinks['l2p'][$details['id']][0]]['files'][$fileGrpThumb];
320
                    break;
321
                }
322
            }
323
            // Get page/track number of the first page/track related to this structure element.
324
            $details['pagination'] = $this->physicalStructureInfo[$this->smLinks['l2p'][$details['id']][0]]['orderlabel'];
325
        } elseif ($details['id'] == $this->_getToplevelId()) {
326
            // Point to self if this is the toplevel structure.
327
            $details['points'] = 1;
328
            $fileGrpsThumb = GeneralUtility::trimExplode(',', $extConf['fileGrpThumbs']);
329
            while ($fileGrpThumb = array_shift($fileGrpsThumb)) {
330
                if (
331
                    !empty($this->physicalStructure)
332
                    && !empty($this->physicalStructureInfo[$this->physicalStructure[1]]['files'][$fileGrpThumb])
333
                ) {
334
                    $details['thumbnailId'] = $this->physicalStructureInfo[$this->physicalStructure[1]]['files'][$fileGrpThumb];
335
                    break;
336
                }
337
            }
338
        }
339
        // Get the files this structure element is pointing at.
340
        $details['files'] = [];
341
        $fileUse = $this->_getFileGrps();
342
        // Get the file representations from fileSec node.
343
        foreach ($structure->children('http://www.loc.gov/METS/')->fptr as $fptr) {
344
            // Check if file has valid @USE attribute.
345
            if (!empty($fileUse[(string) $fptr->attributes()->FILEID])) {
0 ignored issues
show
Bug introduced by
The method attributes() 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

345
            if (!empty($fileUse[(string) $fptr->/** @scrutinizer ignore-call */ attributes()->FILEID])) {

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...
346
                $details['files'][$fileUse[(string) $fptr->attributes()->FILEID]] = (string) $fptr->attributes()->FILEID;
347
            }
348
        }
349
        // Keep for later usage.
350
        $this->logicalUnits[$details['id']] = $details;
351
        // Walk the structure recursively? And are there any children of the current element?
352
        if (
353
            $recursive
354
            && count($structure->children('http://www.loc.gov/METS/')->div)
355
        ) {
356
            $details['children'] = [];
357
            foreach ($structure->children('http://www.loc.gov/METS/')->div as $child) {
358
                // Repeat for all children.
359
                $details['children'][] = $this->getLogicalStructureInfo($child, true);
0 ignored issues
show
Bug introduced by
It seems like $child can also be of type null; however, parameter $structure of Kitodo\Dlf\Common\MetsDo...tLogicalStructureInfo() does only seem to accept SimpleXMLElement, 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

359
                $details['children'][] = $this->getLogicalStructureInfo(/** @scrutinizer ignore-type */ $child, true);
Loading history...
360
            }
361
        }
362
        return $details;
363
    }
364
365
    private function getLogicalStructureFor3D($details) {
366
        // add description and identifier for 3D objects
367
        if ($details['type'] == 'collection' || $details['type'] == 'object') {
368
            $metadata = $this->getMetadata($details['id']);
369
            $details['description'] = $metadata['description'][0];
370
            $details['identifier'] = $metadata['identifier'][0];
371
        }
372
        return $details;
373
    }
374
375
    /**
376
     * {@inheritDoc}
377
     * @see \Kitodo\Dlf\Common\Doc::getMetadata()
378
     */
379
    public function getMetadata($id, $cPid = 0)
380
    {
381
        // Make sure $cPid is a non-negative integer.
382
        $cPid = max(intval($cPid), 0);
383
        // If $cPid is not given, try to get it elsewhere.
384
        if (
385
            !$cPid
386
            && ($this->cPid || $this->pid)
387
        ) {
388
            // Retain current PID.
389
            $cPid = ($this->cPid ? $this->cPid : $this->pid);
390
        } elseif (!$cPid) {
391
            $this->logger->warning('Invalid PID ' . $cPid . ' for metadata definitions');
392
            return [];
393
        }
394
        // Get metadata from parsed metadata array if available.
395
        if (
396
            !empty($this->metadataArray[$id])
397
            && $this->metadataArray[0] == $cPid
398
        ) {
399
            return $this->metadataArray[$id];
400
        }
401
        // Initialize metadata array with empty values.
402
        $metadata = [
403
            'title' => [],
404
            'title_sorting' => [],
405
            'description' => [],
406
            'author' => [],
407
            'place' => [],
408
            'year' => [],
409
            'prod_id' => [],
410
            'record_id' => [],
411
            'opac_id' => [],
412
            'union_id' => [],
413
            'urn' => [],
414
            'purl' => [],
415
            'type' => [],
416
            'volume' => [],
417
            'volume_sorting' => [],
418
            'license' => [],
419
            'terms' => [],
420
            'restrictions' => [],
421
            'out_of_print' => [],
422
            'rights_info' => [],
423
            'collection' => [],
424
            'owner' => [],
425
            'mets_label' => [],
426
            'mets_orderlabel' => [],
427
            'document_format' => ['METS'],
428
        ];
429
        // Get the logical structure node's @DMDID.
430
        if (!empty($this->logicalUnits[$id])) {
431
            $dmdIds = $this->logicalUnits[$id]['dmdId'];
432
        } else {
433
            $dmdIds = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@ID="' . $id . '"]/@DMDID');
434
            $dmdIds = (string) $dmdIds[0];
435
        }
436
        if (!empty($dmdIds)) {
437
            // Handle multiple DMDIDs separately.
438
            $dmdIds = explode(' ', $dmdIds);
439
            $hasSupportedMetadata = false;
440
        } else {
441
            // There is no dmdSec for this structure node.
442
            return [];
443
        }
444
        // Load available metadata formats and dmdSecs.
445
        $this->loadFormats();
446
        $this->_getDmdSec();
447
        foreach ($dmdIds as $dmdId) {
448
            // Is this metadata format supported?
449
            if (!empty($this->formats[$this->dmdSec[$dmdId]['type']])) {
450
                if (!empty($this->formats[$this->dmdSec[$dmdId]['type']]['class'])) {
451
                    $class = $this->formats[$this->dmdSec[$dmdId]['type']]['class'];
452
                    // Get the metadata from class.
453
                    if (
454
                        class_exists($class)
455
                        && ($obj = GeneralUtility::makeInstance($class)) instanceof MetadataInterface
456
                    ) {
457
                        $obj->extractMetadata($this->dmdSec[$dmdId]['xml'], $metadata);
458
                    } else {
459
                        $this->logger->warning('Invalid class/method "' . $class . '->extractMetadata()" for metadata format "' . $this->dmdSec[$dmdId]['type'] . '"');
460
                    }
461
                }
462
            } else {
463
                $this->logger->notice('Unsupported metadata format "' . $this->dmdSec[$dmdId]['type'] . '" in dmdSec with @ID "' . $dmdId . '"');
464
                // Continue searching for supported metadata with next @DMDID.
465
                continue;
466
            }
467
            // Get the structure's type.
468
            if (!empty($this->logicalUnits[$id])) {
469
                $metadata['type'] = [$this->logicalUnits[$id]['type']];
470
            } else {
471
                $struct = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@ID="' . $id . '"]/@TYPE');
472
                if (!empty($struct)) {
473
                    $metadata['type'] = [(string) $struct[0]];
474
                }
475
            }
476
            // Get the additional metadata from database.
477
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
478
                ->getQueryBuilderForTable('tx_dlf_metadata');
479
            // Get hidden records, too.
480
            $queryBuilder
481
                ->getRestrictions()
482
                ->removeByType(HiddenRestriction::class);
483
            // Get all metadata with configured xpath and applicable format first.
484
            $resultWithFormat = $queryBuilder
485
                ->select(
486
                    'tx_dlf_metadata.index_name AS index_name',
487
                    'tx_dlf_metadataformat_joins.xpath AS xpath',
488
                    'tx_dlf_metadataformat_joins.xpath_sorting AS xpath_sorting',
489
                    'tx_dlf_metadata.is_sortable AS is_sortable',
490
                    'tx_dlf_metadata.default_value AS default_value',
491
                    'tx_dlf_metadata.format AS format'
492
                )
493
                ->from('tx_dlf_metadata')
494
                ->innerJoin(
495
                    'tx_dlf_metadata',
496
                    'tx_dlf_metadataformat',
497
                    'tx_dlf_metadataformat_joins',
498
                    $queryBuilder->expr()->eq(
499
                        'tx_dlf_metadataformat_joins.parent_id',
500
                        'tx_dlf_metadata.uid'
501
                    )
502
                )
503
                ->innerJoin(
504
                    'tx_dlf_metadataformat_joins',
505
                    'tx_dlf_formats',
506
                    'tx_dlf_formats_joins',
507
                    $queryBuilder->expr()->eq(
508
                        'tx_dlf_formats_joins.uid',
509
                        'tx_dlf_metadataformat_joins.encoded'
510
                    )
511
                )
512
                ->where(
513
                    $queryBuilder->expr()->eq('tx_dlf_metadata.pid', intval($cPid)),
514
                    $queryBuilder->expr()->eq('tx_dlf_metadata.l18n_parent', 0),
515
                    $queryBuilder->expr()->eq('tx_dlf_metadataformat_joins.pid', intval($cPid)),
516
                    $queryBuilder->expr()->eq('tx_dlf_formats_joins.type', $queryBuilder->createNamedParameter($this->dmdSec[$dmdId]['type']))
517
                )
518
                ->execute();
519
            // Get all metadata without a format, but with a default value next.
520
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
521
                ->getQueryBuilderForTable('tx_dlf_metadata');
522
            // Get hidden records, too.
523
            $queryBuilder
524
                ->getRestrictions()
525
                ->removeByType(HiddenRestriction::class);
526
            $resultWithoutFormat = $queryBuilder
527
                ->select(
528
                    'tx_dlf_metadata.index_name AS index_name',
529
                    'tx_dlf_metadata.is_sortable AS is_sortable',
530
                    'tx_dlf_metadata.default_value AS default_value',
531
                    'tx_dlf_metadata.format AS format'
532
                )
533
                ->from('tx_dlf_metadata')
534
                ->where(
535
                    $queryBuilder->expr()->eq('tx_dlf_metadata.pid', intval($cPid)),
536
                    $queryBuilder->expr()->eq('tx_dlf_metadata.l18n_parent', 0),
537
                    $queryBuilder->expr()->eq('tx_dlf_metadata.format', 0),
538
                    $queryBuilder->expr()->neq('tx_dlf_metadata.default_value', $queryBuilder->createNamedParameter(''))
539
                )
540
                ->execute();
541
            // Merge both result sets.
542
            $allResults = array_merge($resultWithFormat->fetchAll(), $resultWithoutFormat->fetchAll());
543
            // We need a \DOMDocument here, because SimpleXML doesn't support XPath functions properly.
544
            $domNode = dom_import_simplexml($this->dmdSec[$dmdId]['xml']);
545
            $domXPath = new \DOMXPath($domNode->ownerDocument);
0 ignored issues
show
Bug introduced by
It seems like $domNode->ownerDocument can also be of type null; however, parameter $document of DOMXPath::__construct() does only seem to accept DOMDocument, 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

545
            $domXPath = new \DOMXPath(/** @scrutinizer ignore-type */ $domNode->ownerDocument);
Loading history...
546
            $this->registerNamespaces($domXPath);
547
            // OK, now make the XPath queries.
548
            foreach ($allResults as $resArray) {
549
                // Set metadata field's value(s).
550
                if (
551
                    $resArray['format'] > 0
552
                    && !empty($resArray['xpath'])
553
                    && ($values = $domXPath->evaluate($resArray['xpath'], $domNode))
554
                ) {
555
                    if (
556
                        $values instanceof \DOMNodeList
557
                        && $values->length > 0
558
                    ) {
559
                        $metadata[$resArray['index_name']] = [];
560
                        foreach ($values as $value) {
561
                            $metadata[$resArray['index_name']][] = trim((string) $value->nodeValue);
562
                        }
563
                    } elseif (!($values instanceof \DOMNodeList)) {
564
                        $metadata[$resArray['index_name']] = [trim((string) $values)];
565
                    }
566
                }
567
                // Set default value if applicable.
568
                if (
569
                    empty($metadata[$resArray['index_name']][0])
570
                    && strlen($resArray['default_value']) > 0
571
                ) {
572
                    $metadata[$resArray['index_name']] = [$resArray['default_value']];
573
                }
574
                // Set sorting value if applicable.
575
                if (
576
                    !empty($metadata[$resArray['index_name']])
577
                    && $resArray['is_sortable']
578
                ) {
579
                    if (
580
                        $resArray['format'] > 0
581
                        && !empty($resArray['xpath_sorting'])
582
                        && ($values = $domXPath->evaluate($resArray['xpath_sorting'], $domNode))
583
                    ) {
584
                        if (
585
                            $values instanceof \DOMNodeList
586
                            && $values->length > 0
587
                        ) {
588
                            $metadata[$resArray['index_name'] . '_sorting'][0] = trim((string) $values->item(0)->nodeValue);
589
                        } elseif (!($values instanceof \DOMNodeList)) {
590
                            $metadata[$resArray['index_name'] . '_sorting'][0] = trim((string) $values);
591
                        }
592
                    }
593
                    if (empty($metadata[$resArray['index_name'] . '_sorting'][0])) {
594
                        $metadata[$resArray['index_name'] . '_sorting'][0] = $metadata[$resArray['index_name']][0];
595
                    }
596
                }
597
            }
598
            // Set title to empty string if not present.
599
            if (empty($metadata['title'][0])) {
600
                $metadata['title'][0] = '';
601
                $metadata['title_sorting'][0] = '';
602
            }
603
            // Extract metadata only from first supported dmdSec.
604
            $hasSupportedMetadata = true;
605
            break;
606
        }
607
        if ($hasSupportedMetadata) {
608
            return $metadata;
609
        } else {
610
            $this->logger->warning('No supported metadata found for logical structure with @ID "' . $id . '"');
611
            return [];
612
        }
613
    }
614
615
    /**
616
     * {@inheritDoc}
617
     * @see \Kitodo\Dlf\Common\Doc::getFullText()
618
     */
619
    public function getFullText($id)
620
    {
621
        $fullText = '';
622
623
        // Load fileGrps and check for full text files.
624
        $this->_getFileGrps();
625
        if ($this->hasFulltext) {
626
            $fullText = $this->getFullTextFromXml($id);
627
        }
628
        return $fullText;
629
    }
630
631
    /**
632
     * {@inheritDoc}
633
     * @see Doc::getStructureDepth()
634
     */
635
    public function getStructureDepth($logId)
636
    {
637
        $ancestors = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@ID="' . $logId . '"]/ancestor::*');
638
        if (!empty($ancestors)) {
639
            return count($ancestors);
640
        } else {
641
            return 0;
642
        }
643
    }
644
645
    /**
646
     * {@inheritDoc}
647
     * @see \Kitodo\Dlf\Common\Doc::init()
648
     */
649
    protected function init($location)
650
    {
651
        $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(get_class($this));
652
        // Get METS node from XML file.
653
        $this->registerNamespaces($this->xml);
654
        $mets = $this->xml->xpath('//mets:mets');
655
        if (!empty($mets)) {
656
            $this->mets = $mets[0];
657
            // Register namespaces.
658
            $this->registerNamespaces($this->mets);
659
        } else {
660
            if (!empty($location)) {
661
                $this->logger->error('No METS part found in document with location "' . $location . '".');
662
            } else if (!empty($this->recordId)) {
663
                $this->logger->error('No METS part found in document with recordId "' . $this->recordId . '".');
664
            } else {
665
                $this->logger->error('No METS part found in current document.');
666
            }
667
        }
668
    }
669
670
    /**
671
     * {@inheritDoc}
672
     * @see \Kitodo\Dlf\Common\Doc::loadLocation()
673
     */
674
    protected function loadLocation($location)
675
    {
676
        $fileResource = Helper::getUrl($location);
677
        if ($fileResource !== false) {
678
            $xml = Helper::getXmlFileAsString($fileResource);
679
            // Set some basic properties.
680
            if ($xml !== false) {
681
                $this->xml = $xml;
682
                return true;
683
            }
684
        }
685
        $this->logger->error('Could not load XML file from "' . $location . '"');
686
        return false;
687
    }
688
689
    /**
690
     * {@inheritDoc}
691
     * @see \Kitodo\Dlf\Common\Doc::ensureHasFulltextIsSet()
692
     */
693
    protected function ensureHasFulltextIsSet()
694
    {
695
        // Are the fileGrps already loaded?
696
        if (!$this->fileGrpsLoaded) {
697
            $this->_getFileGrps();
698
        }
699
    }
700
701
    /**
702
     * {@inheritDoc}
703
     * @see Doc::setPreloadedDocument()
704
     */
705
    protected function setPreloadedDocument($preloadedDocument)
706
    {
707
708
        if ($preloadedDocument instanceof \SimpleXMLElement) {
709
            $this->xml = $preloadedDocument;
710
            return true;
711
        }
712
        return false;
713
    }
714
715
    /**
716
     * {@inheritDoc}
717
     * @see Doc::getDocument()
718
     */
719
    protected function getDocument()
720
    {
721
        return $this->mets;
722
    }
723
724
    /**
725
     * This builds an array of the document's dmdSecs
726
     *
727
     * @access protected
728
     *
729
     * @return array Array of dmdSecs with their IDs as array key
730
     */
731
    protected function _getDmdSec()
732
    {
733
        if (!$this->dmdSecLoaded) {
734
            // Get available data formats.
735
            $this->loadFormats();
736
            // Get dmdSec nodes from METS.
737
            $dmdIds = $this->mets->xpath('./mets:dmdSec/@ID');
738
            if (!empty($dmdIds)) {
739
                foreach ($dmdIds as $dmdId) {
740
                    if ($type = $this->mets->xpath('./mets:dmdSec[@ID="' . (string) $dmdId . '"]/mets:mdWrap[not(@MDTYPE="OTHER")]/@MDTYPE')) {
741
                        if (!empty($this->formats[(string) $type[0]])) {
742
                            $type = (string) $type[0];
743
                            $xml = $this->mets->xpath('./mets:dmdSec[@ID="' . (string) $dmdId . '"]/mets:mdWrap[@MDTYPE="' . $type . '"]/mets:xmlData/' . strtolower($type) . ':' . $this->formats[$type]['rootElement']);
744
                        }
745
                    } elseif ($type = $this->mets->xpath('./mets:dmdSec[@ID="' . (string) $dmdId . '"]/mets:mdWrap[@MDTYPE="OTHER"]/@OTHERMDTYPE')) {
746
                        if (!empty($this->formats[(string) $type[0]])) {
747
                            $type = (string) $type[0];
748
                            $xml = $this->mets->xpath('./mets:dmdSec[@ID="' . (string) $dmdId . '"]/mets:mdWrap[@MDTYPE="OTHER"][@OTHERMDTYPE="' . $type . '"]/mets:xmlData/' . strtolower($type) . ':' . $this->formats[$type]['rootElement']);
749
                        }
750
                    }
751
                    if (!empty($xml)) {
752
                        $this->dmdSec[(string) $dmdId]['type'] = $type;
753
                        $this->dmdSec[(string) $dmdId]['xml'] = $xml[0];
754
                        $this->registerNamespaces($this->dmdSec[(string) $dmdId]['xml']);
755
                    }
756
                }
757
            }
758
            $this->dmdSecLoaded = true;
759
        }
760
        return $this->dmdSec;
761
    }
762
763
    /**
764
     * This builds the file ID -> USE concordance
765
     *
766
     * @access protected
767
     *
768
     * @return array Array of file use groups with file IDs
769
     */
770
    protected function _getFileGrps()
771
    {
772
        if (!$this->fileGrpsLoaded) {
773
            // Get configured USE attributes.
774
            $extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
775
            $useGrps = GeneralUtility::trimExplode(',', $extConf['fileGrpImages']);
776
            if (!empty($extConf['fileGrpThumbs'])) {
777
                $useGrps = array_merge($useGrps, GeneralUtility::trimExplode(',', $extConf['fileGrpThumbs']));
778
            }
779
            if (!empty($extConf['fileGrpDownload'])) {
780
                $useGrps = array_merge($useGrps, GeneralUtility::trimExplode(',', $extConf['fileGrpDownload']));
781
            }
782
            if (!empty($extConf['fileGrpFulltext'])) {
783
                $useGrps = array_merge($useGrps, GeneralUtility::trimExplode(',', $extConf['fileGrpFulltext']));
784
            }
785
            if (!empty($extConf['fileGrpAudio'])) {
786
                $useGrps = array_merge($useGrps, GeneralUtility::trimExplode(',', $extConf['fileGrpAudio']));
787
            }
788
            // Get all file groups.
789
            $fileGrps = $this->mets->xpath('./mets:fileSec/mets:fileGrp');
790
            if (!empty($fileGrps)) {
791
                // Build concordance for configured USE attributes.
792
                foreach ($fileGrps as $fileGrp) {
793
                    if (in_array((string) $fileGrp['USE'], $useGrps)) {
794
                        foreach ($fileGrp->children('http://www.loc.gov/METS/')->file as $file) {
795
                            $this->fileGrps[(string) $file->attributes()->ID] = (string) $fileGrp['USE'];
0 ignored issues
show
Bug introduced by
The method attributes() 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

795
                            $this->fileGrps[(string) $file->/** @scrutinizer ignore-call */ attributes()->ID] = (string) $fileGrp['USE'];

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...
796
                        }
797
                    }
798
                }
799
            }
800
            // Are there any fulltext files available?
801
            if (
802
                !empty($extConf['fileGrpFulltext'])
803
                && array_intersect(GeneralUtility::trimExplode(',', $extConf['fileGrpFulltext']), $this->fileGrps) !== []
804
            ) {
805
                $this->hasFulltext = true;
806
            }
807
            $this->fileGrpsLoaded = true;
808
        }
809
        return $this->fileGrps;
810
    }
811
812
    /**
813
     * {@inheritDoc}
814
     * @see \Kitodo\Dlf\Common\Doc::prepareMetadataArray()
815
     */
816
    protected function prepareMetadataArray($cPid)
817
    {
818
        $ids = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@DMDID]/@ID');
819
        // Get all logical structure nodes with metadata.
820
        if (!empty($ids)) {
821
            foreach ($ids as $id) {
822
                $this->metadataArray[(string) $id] = $this->getMetadata((string) $id, $cPid);
823
            }
824
        }
825
        // Set current PID for metadata definitions.
826
    }
827
828
    /**
829
     * This returns $this->mets via __get()
830
     *
831
     * @access protected
832
     *
833
     * @return \SimpleXMLElement The XML's METS part as \SimpleXMLElement object
834
     */
835
    protected function _getMets()
836
    {
837
        return $this->mets;
838
    }
839
840
    /**
841
     * {@inheritDoc}
842
     * @see \Kitodo\Dlf\Common\Doc::_getPhysicalStructure()
843
     */
844
    protected function _getPhysicalStructure()
845
    {
846
        // Is there no physical structure array yet?
847
        if (!$this->physicalStructureLoaded) {
848
            // Does the document have a structMap node of type "PHYSICAL"?
849
            $elementNodes = $this->mets->xpath('./mets:structMap[@TYPE="PHYSICAL"]/mets:div[@TYPE="physSequence"]/mets:div');
850
            if (!empty($elementNodes)) {
851
                // Get file groups.
852
                $fileUse = $this->_getFileGrps();
853
                // Get the physical sequence's metadata.
854
                $physNode = $this->mets->xpath('./mets:structMap[@TYPE="PHYSICAL"]/mets:div[@TYPE="physSequence"]');
855
                $physSeq[0] = (string) $physNode[0]['ID'];
856
                $this->physicalStructureInfo[$physSeq[0]]['id'] = (string) $physNode[0]['ID'];
857
                $this->physicalStructureInfo[$physSeq[0]]['dmdId'] = (isset($physNode[0]['DMDID']) ? (string) $physNode[0]['DMDID'] : '');
858
                $this->physicalStructureInfo[$physSeq[0]]['order'] = (isset($physNode[0]['ORDER']) ? (string) $physNode[0]['ORDER'] : '');
859
                $this->physicalStructureInfo[$physSeq[0]]['label'] = (isset($physNode[0]['LABEL']) ? (string) $physNode[0]['LABEL'] : '');
860
                $this->physicalStructureInfo[$physSeq[0]]['orderlabel'] = (isset($physNode[0]['ORDERLABEL']) ? (string) $physNode[0]['ORDERLABEL'] : '');
861
                $this->physicalStructureInfo[$physSeq[0]]['type'] = (string) $physNode[0]['TYPE'];
862
                $this->physicalStructureInfo[$physSeq[0]]['contentIds'] = (isset($physNode[0]['CONTENTIDS']) ? (string) $physNode[0]['CONTENTIDS'] : '');
863
                // Get the file representations from fileSec node.
864
                foreach ($physNode[0]->children('http://www.loc.gov/METS/')->fptr as $fptr) {
865
                    // Check if file has valid @USE attribute.
866
                    if (!empty($fileUse[(string) $fptr->attributes()->FILEID])) {
867
                        $this->physicalStructureInfo[$physSeq[0]]['files'][$fileUse[(string) $fptr->attributes()->FILEID]] = (string) $fptr->attributes()->FILEID;
868
                    }
869
                }
870
                // Build the physical elements' array from the physical structMap node.
871
                foreach ($elementNodes as $elementNode) {
872
                    $elements[(int) $elementNode['ORDER']] = (string) $elementNode['ID'];
873
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['id'] = (string) $elementNode['ID'];
874
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['dmdId'] = (isset($elementNode['DMDID']) ? (string) $elementNode['DMDID'] : '');
875
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['order'] = (isset($elementNode['ORDER']) ? (string) $elementNode['ORDER'] : '');
876
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['label'] = (isset($elementNode['LABEL']) ? (string) $elementNode['LABEL'] : '');
877
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['orderlabel'] = (isset($elementNode['ORDERLABEL']) ? (string) $elementNode['ORDERLABEL'] : '');
878
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['type'] = (string) $elementNode['TYPE'];
879
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['contentIds'] = (isset($elementNode['CONTENTIDS']) ? (string) $elementNode['CONTENTIDS'] : '');
880
                    // Get the file representations from fileSec node.
881
                    foreach ($elementNode->children('http://www.loc.gov/METS/')->fptr as $fptr) {
882
                        // Check if file has valid @USE attribute.
883
                        if (!empty($fileUse[(string) $fptr->attributes()->FILEID])) {
884
                            $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['files'][$fileUse[(string) $fptr->attributes()->FILEID]] = (string) $fptr->attributes()->FILEID;
885
                        }
886
                    }
887
                }
888
                // Sort array by keys (= @ORDER).
889
                if (ksort($elements)) {
890
                    // Set total number of pages/tracks.
891
                    $this->numPages = count($elements);
892
                    // Merge and re-index the array to get nice numeric indexes.
893
                    $this->physicalStructure = array_merge($physSeq, $elements);
894
                }
895
            }
896
            $this->physicalStructureLoaded = true;
897
        }
898
        return $this->physicalStructure;
899
    }
900
901
    /**
902
     * {@inheritDoc}
903
     * @see \Kitodo\Dlf\Common\Doc::_getSmLinks()
904
     */
905
    protected function _getSmLinks()
906
    {
907
        if (!$this->smLinksLoaded) {
908
            $smLinks = $this->mets->xpath('./mets:structLink/mets:smLink');
909
            if (!empty($smLinks)) {
910
                foreach ($smLinks as $smLink) {
911
                    $this->smLinks['l2p'][(string) $smLink->attributes('http://www.w3.org/1999/xlink')->from][] = (string) $smLink->attributes('http://www.w3.org/1999/xlink')->to;
912
                    $this->smLinks['p2l'][(string) $smLink->attributes('http://www.w3.org/1999/xlink')->to][] = (string) $smLink->attributes('http://www.w3.org/1999/xlink')->from;
913
                }
914
            }
915
            $this->smLinksLoaded = true;
916
        }
917
        return $this->smLinks;
918
    }
919
920
    /**
921
     * {@inheritDoc}
922
     * @see \Kitodo\Dlf\Common\Doc::_getThumbnail()
923
     */
924
    protected function _getThumbnail($forceReload = false)
925
    {
926
        if (
927
            !$this->thumbnailLoaded
928
            || $forceReload
929
        ) {
930
            // Retain current PID.
931
            $cPid = ($this->cPid ? $this->cPid : $this->pid);
932
            if (!$cPid) {
933
                $this->logger->error('Invalid PID ' . $cPid . ' for structure definitions');
934
                $this->thumbnailLoaded = true;
935
                return $this->thumbnail;
936
            }
937
            // Load extension configuration.
938
            $extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
939
            if (empty($extConf['fileGrpThumbs'])) {
940
                $this->logger->warning('No fileGrp for thumbnails specified');
941
                $this->thumbnailLoaded = true;
942
                return $this->thumbnail;
943
            }
944
            $strctId = $this->_getToplevelId();
945
            $metadata = $this->getTitledata($cPid);
946
947
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
948
                ->getQueryBuilderForTable('tx_dlf_structures');
949
950
            // Get structure element to get thumbnail from.
951
            $result = $queryBuilder
952
                ->select('tx_dlf_structures.thumbnail AS thumbnail')
953
                ->from('tx_dlf_structures')
954
                ->where(
955
                    $queryBuilder->expr()->eq('tx_dlf_structures.pid', intval($cPid)),
956
                    $queryBuilder->expr()->eq('tx_dlf_structures.index_name', $queryBuilder->expr()->literal($metadata['type'][0])),
957
                    Helper::whereExpression('tx_dlf_structures')
958
                )
959
                ->setMaxResults(1)
960
                ->execute();
961
962
            $allResults = $result->fetchAll();
963
964
            if (count($allResults) == 1) {
965
                $resArray = $allResults[0];
966
                // Get desired thumbnail structure if not the toplevel structure itself.
967
                if (!empty($resArray['thumbnail'])) {
968
                    $strctType = Helper::getIndexNameFromUid($resArray['thumbnail'], 'tx_dlf_structures', $cPid);
969
                    // Check if this document has a structure element of the desired type.
970
                    $strctIds = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@TYPE="' . $strctType . '"]/@ID');
971
                    if (!empty($strctIds)) {
972
                        $strctId = (string) $strctIds[0];
973
                    }
974
                }
975
                // Load smLinks.
976
                $this->_getSmLinks();
977
                // Get thumbnail location.
978
                $fileGrpsThumb = GeneralUtility::trimExplode(',', $extConf['fileGrpThumbs']);
979
                while ($fileGrpThumb = array_shift($fileGrpsThumb)) {
980
                    if (
981
                        $this->_getPhysicalStructure()
982
                        && !empty($this->smLinks['l2p'][$strctId])
983
                        && !empty($this->physicalStructureInfo[$this->smLinks['l2p'][$strctId][0]]['files'][$fileGrpThumb])
984
                    ) {
985
                        $this->thumbnail = $this->getFileLocation($this->physicalStructureInfo[$this->smLinks['l2p'][$strctId][0]]['files'][$fileGrpThumb]);
986
                        break;
987
                    } elseif (!empty($this->physicalStructureInfo[$this->physicalStructure[1]]['files'][$fileGrpThumb])) {
988
                        $this->thumbnail = $this->getFileLocation($this->physicalStructureInfo[$this->physicalStructure[1]]['files'][$fileGrpThumb]);
989
                        break;
990
                    }
991
                }
992
            } else {
993
                $this->logger->error('No structure of type "' . $metadata['type'][0] . '" found in database');
994
            }
995
            $this->thumbnailLoaded = true;
996
        }
997
        return $this->thumbnail;
998
    }
999
1000
    /**
1001
     * {@inheritDoc}
1002
     * @see \Kitodo\Dlf\Common\Doc::_getToplevelId()
1003
     */
1004
    protected function _getToplevelId()
1005
    {
1006
        if (empty($this->toplevelId)) {
1007
            // Get all logical structure nodes with metadata, but without associated METS-Pointers.
1008
            $divs = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@DMDID and not(./mets:mptr)]');
1009
            if (!empty($divs)) {
1010
                // Load smLinks.
1011
                $this->_getSmLinks();
1012
                foreach ($divs as $div) {
1013
                    $id = (string) $div['ID'];
1014
                    // Are there physical structure nodes for this logical structure?
1015
                    if (array_key_exists($id, $this->smLinks['l2p'])) {
1016
                        // Yes. That's what we're looking for.
1017
                        $this->toplevelId = $id;
1018
                        break;
1019
                    } elseif (empty($this->toplevelId)) {
1020
                        // No. Remember this anyway, but keep looking for a better one.
1021
                        $this->toplevelId = $id;
1022
                    }
1023
                }
1024
            }
1025
        }
1026
        return $this->toplevelId;
1027
    }
1028
1029
    /**
1030
     * This magic method is executed prior to any serialization of the object
1031
     * @see __wakeup()
1032
     *
1033
     * @access public
1034
     *
1035
     * @return array Properties to be serialized
1036
     */
1037
    public function __sleep()
1038
    {
1039
        // \SimpleXMLElement objects can't be serialized, thus save the XML as string for serialization
1040
        $this->asXML = $this->xml->asXML();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->xml->asXML() can also be of type true. However, the property $asXML is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1041
        return ['uid', 'pid', 'recordId', 'parentId', 'asXML'];
1042
    }
1043
1044
    /**
1045
     * This magic method is used for setting a string value for the object
1046
     *
1047
     * @access public
1048
     *
1049
     * @return string String representing the METS object
1050
     */
1051
    public function __toString()
1052
    {
1053
        $xml = new \DOMDocument('1.0', 'utf-8');
1054
        $xml->appendChild($xml->importNode(dom_import_simplexml($this->mets), true));
1055
        $xml->formatOutput = true;
1056
        return $xml->saveXML();
1057
    }
1058
1059
    /**
1060
     * This magic method is executed after the object is deserialized
1061
     * @see __sleep()
1062
     *
1063
     * @access public
1064
     *
1065
     * @return void
1066
     */
1067
    public function __wakeup()
1068
    {
1069
        $xml = Helper::getXmlFileAsString($this->asXML);
1070
        if ($xml !== false) {
1071
            $this->asXML = '';
1072
            $this->xml = $xml;
1073
            // Rebuild the unserializable properties.
1074
            $this->init('');
1075
        } else {
1076
            $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(static::class);
1077
            $this->logger->error('Could not load XML after deserialization');
1078
        }
1079
    }
1080
}
1081