Completed
Push — master ( f65802...ddb531 )
by
unknown
39:08 queued 15:48
created

ResourceFactory::getFileReferenceData()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 21
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 16
nc 3
nop 2
dl 0
loc 21
rs 9.4222
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
 * It is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License, either version 2
8
 * of the License, or any later version.
9
 *
10
 * For the full copyright and license information, please read the
11
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
 * The TYPO3 project - inspiring people to share!
14
 */
15
16
namespace TYPO3\CMS\Core\Resource;
17
18
use Psr\EventDispatcher\EventDispatcherInterface;
19
use TYPO3\CMS\Backend\Utility\BackendUtility;
20
use TYPO3\CMS\Core\Core\Environment;
21
use TYPO3\CMS\Core\Database\ConnectionPool;
22
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
23
use TYPO3\CMS\Core\Resource\Collection\FileCollectionRegistry;
24
use TYPO3\CMS\Core\Resource\Driver\DriverRegistry;
25
use TYPO3\CMS\Core\Resource\Event\AfterResourceStorageInitializationEvent;
26
use TYPO3\CMS\Core\Resource\Event\BeforeResourceStorageInitializationEvent;
27
use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException;
28
use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
29
use TYPO3\CMS\Core\Resource\Index\FileIndexRepository;
30
use TYPO3\CMS\Core\Resource\Index\Indexer;
31
use TYPO3\CMS\Core\Service\FlexFormService;
32
use TYPO3\CMS\Core\SingletonInterface;
33
use TYPO3\CMS\Core\Utility\GeneralUtility;
34
use TYPO3\CMS\Core\Utility\MathUtility;
35
use TYPO3\CMS\Core\Utility\PathUtility;
36
37
/**
38
 * Factory class for FAL objects
39
 */
40
class ResourceFactory implements SingletonInterface
41
{
42
    /**
43
     * @var ResourceStorage[]
44
     */
45
    protected $storageInstances = [];
46
47
    /**
48
     * @var Collection\AbstractFileCollection[]
49
     */
50
    protected $collectionInstances = [];
51
52
    /**
53
     * @var File[]
54
     */
55
    protected $fileInstances = [];
56
57
    /**
58
     * @var FileReference[]
59
     */
60
    protected $fileReferenceInstances = [];
61
62
    /**
63
     * A list of the base paths of "local" driver storages. Used to make the detection of base paths easier.
64
     *
65
     * @var array
66
     */
67
    protected $localDriverStorageCache;
68
69
    /**
70
     * @var EventDispatcherInterface
71
     */
72
    protected $eventDispatcher;
73
74
    /**
75
     * @param EventDispatcherInterface $eventDispatcher
76
     */
77
    public function __construct(EventDispatcherInterface $eventDispatcher)
78
    {
79
        $this->eventDispatcher = $eventDispatcher;
80
    }
81
82
    /**
83
     * Creates a driver object for a specified storage object.
84
     *
85
     * @param string $driverIdentificationString The driver class (or identifier) to use.
86
     * @param array $driverConfiguration The configuration of the storage
87
     * @return Driver\DriverInterface
88
     * @throws \InvalidArgumentException
89
     */
90
    public function getDriverObject($driverIdentificationString, array $driverConfiguration)
91
    {
92
        /** @var Driver\DriverRegistry $driverRegistry */
93
        $driverRegistry = GeneralUtility::makeInstance(DriverRegistry::class);
94
        $driverClass = $driverRegistry->getDriverClass($driverIdentificationString);
95
        $driverObject = GeneralUtility::makeInstance($driverClass, $driverConfiguration);
96
        return $driverObject;
97
    }
98
99
    /**
100
     * Returns the Default Storage
101
     *
102
     * The Default Storage is considered to be the replacement for the fileadmin/ construct.
103
     * It is automatically created with the setting fileadminDir from install tool.
104
     * getDefaultStorage->getDefaultFolder() will get you fileadmin/user_upload/ in a standard
105
     * TYPO3 installation.
106
     *
107
     * @return ResourceStorage|null
108
     */
109
    public function getDefaultStorage()
110
    {
111
        /** @var StorageRepository $storageRepository */
112
        $storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
113
114
        $allStorages = $storageRepository->findAll();
115
        foreach ($allStorages as $storage) {
116
            if ($storage->isDefault()) {
117
                return $storage;
118
            }
119
        }
120
        return null;
121
    }
122
    /**
123
     * Creates an instance of the storage from given UID. The $recordData can
124
     * be supplied to increase performance.
125
     *
126
     * @param int $uid The uid of the storage to instantiate.
127
     * @param array $recordData The record row from database.
128
     * @param string $fileIdentifier Identifier for a file. Used for auto-detection of a storage, but only if $uid === 0 (Local default storage) is used
129
     *
130
     * @throws \InvalidArgumentException
131
     * @return ResourceStorage
132
     */
133
    public function getStorageObject($uid, array $recordData = [], &$fileIdentifier = null)
134
    {
135
        if (!is_numeric($uid)) {
0 ignored issues
show
introduced by
The condition is_numeric($uid) is always true.
Loading history...
136
            throw new \InvalidArgumentException('The UID of storage has to be numeric. UID given: "' . $uid . '"', 1314085991);
137
        }
138
        $uid = (int)$uid;
139
        if ($uid === 0 && $fileIdentifier !== null) {
140
            $uid = $this->findBestMatchingStorageByLocalPath($fileIdentifier);
141
        }
142
        if (empty($this->storageInstances[$uid])) {
143
            $storageConfiguration = null;
144
            $storageObject = null;
145
            /** @var BeforeResourceStorageInitializationEvent $event */
146
            $event = $this->eventDispatcher->dispatch(new BeforeResourceStorageInitializationEvent($uid, $recordData, $fileIdentifier));
147
            $recordData = $event->getRecord();
148
            $uid = $event->getStorageUid();
149
            $fileIdentifier = $event->getFileIdentifier();
150
            // If the built-in storage with UID=0 is requested:
151
            if ($uid === 0) {
152
                $recordData = [
153
                    'uid' => 0,
154
                    'pid' => 0,
155
                    'name' => 'Fallback Storage',
156
                    'description' => 'Internal storage, mounting the main TYPO3_site directory.',
157
                    'driver' => 'Local',
158
                    'processingfolder' => 'typo3temp/assets/_processed_/',
159
                    // legacy code
160
                    'configuration' => '',
161
                    'is_online' => true,
162
                    'is_browsable' => true,
163
                    'is_public' => true,
164
                    'is_writable' => true,
165
                    'is_default' => false,
166
                ];
167
                $storageConfiguration = [
168
                    'basePath' => '/',
169
                    'pathType' => 'relative'
170
                ];
171
            } elseif (count($recordData) === 0 || (int)$recordData['uid'] !== $uid) {
172
                /** @var StorageRepository $storageRepository */
173
                $storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
174
                /** @var ResourceStorage $storageObject */
175
                $storageObject = $storageRepository->findByUid($uid);
176
            }
177
            if (!$storageObject instanceof ResourceStorage) {
178
                $storageObject = $this->createStorageObject($recordData, $storageConfiguration);
179
            }
180
            $storageObject = $this->eventDispatcher
181
                ->dispatch(new AfterResourceStorageInitializationEvent($storageObject))
182
                ->getStorage();
183
            $this->storageInstances[$uid] = $storageObject;
184
        }
185
        return $this->storageInstances[$uid];
186
    }
187
188
    /**
189
     * Checks whether a file resides within a real storage in local file system.
190
     * If no match is found, uid 0 is returned which is a fallback storage pointing to fileadmin in public web path.
191
     *
192
     * The file identifier is adapted accordingly to match the new storage's base path.
193
     *
194
     * @param string $localPath
195
     *
196
     * @return int
197
     */
198
    protected function findBestMatchingStorageByLocalPath(&$localPath)
199
    {
200
        if ($this->localDriverStorageCache === null) {
201
            $this->initializeLocalStorageCache();
202
        }
203
204
        $bestMatchStorageUid = 0;
205
        $bestMatchLength = 0;
206
        foreach ($this->localDriverStorageCache as $storageUid => $basePath) {
207
            $matchLength = strlen(PathUtility::getCommonPrefix([$basePath, $localPath]));
208
            $basePathLength = strlen($basePath);
209
210
            if ($matchLength >= $basePathLength && $matchLength > $bestMatchLength) {
211
                $bestMatchStorageUid = (int)$storageUid;
212
                $bestMatchLength = $matchLength;
213
            }
214
        }
215
        if ($bestMatchStorageUid !== 0) {
216
            $localPath = substr($localPath, $bestMatchLength);
217
        }
218
        return $bestMatchStorageUid;
219
    }
220
221
    /**
222
     * Creates an array mapping all uids to the basePath of storages using the "local" driver.
223
     */
224
    protected function initializeLocalStorageCache()
225
    {
226
        /** @var StorageRepository $storageRepository */
227
        $storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
228
        /** @var ResourceStorage[] $storageObjects */
229
        $storageObjects = $storageRepository->findByStorageType('Local');
230
231
        $storageCache = [];
232
        foreach ($storageObjects as $localStorage) {
233
            $configuration = $localStorage->getConfiguration();
234
            $storageCache[$localStorage->getUid()] = $configuration['basePath'];
235
        }
236
        $this->localDriverStorageCache = $storageCache;
237
    }
238
239
    /**
240
     * Converts a flexform data string to a flat array with key value pairs
241
     *
242
     * @param string $flexFormData
243
     * @return array Array with key => value pairs of the field data in the FlexForm
244
     */
245
    public function convertFlexFormDataToConfigurationArray($flexFormData)
246
    {
247
        $configuration = [];
248
        if ($flexFormData) {
249
            $flexFormService = GeneralUtility::makeInstance(FlexFormService::class);
250
            $configuration = $flexFormService->convertFlexFormContentToArray($flexFormData);
251
        }
252
        return $configuration;
253
    }
254
255
    /**
256
     * Creates an instance of the collection from given UID. The $recordData can be supplied to increase performance.
257
     *
258
     * @param int $uid The uid of the collection to instantiate.
259
     * @param array $recordData The record row from database.
260
     *
261
     * @throws \InvalidArgumentException
262
     * @return Collection\AbstractFileCollection
263
     */
264
    public function getCollectionObject($uid, array $recordData = [])
265
    {
266
        if (!is_numeric($uid)) {
0 ignored issues
show
introduced by
The condition is_numeric($uid) is always true.
Loading history...
267
            throw new \InvalidArgumentException('The UID of collection has to be numeric. UID given: "' . $uid . '"', 1314085999);
268
        }
269
        if (!$this->collectionInstances[$uid]) {
270
            // Get mount data if not already supplied as argument to this function
271
            if (empty($recordData) || $recordData['uid'] !== $uid) {
272
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_file_collection');
273
                $queryBuilder->getRestrictions()->removeAll()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
274
                $recordData = $queryBuilder->select('*')
275
                    ->from('sys_file_collection')
276
                    ->where(
277
                        $queryBuilder->expr()->eq(
278
                            'uid',
279
                            $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
280
                        )
281
                    )
282
                    ->execute()
283
                    ->fetch();
284
                if (empty($recordData)) {
285
                    throw new \InvalidArgumentException('No collection found for given UID: "' . $uid . '"', 1314085992);
286
                }
287
            }
288
            $collectionObject = $this->createCollectionObject($recordData);
289
            $this->collectionInstances[$uid] = $collectionObject;
290
        }
291
        return $this->collectionInstances[$uid];
292
    }
293
294
    /**
295
     * Creates a collection object.
296
     *
297
     * @param array $collectionData The database row of the sys_file_collection record.
298
     * @return Collection\AbstractFileCollection
299
     */
300
    public function createCollectionObject(array $collectionData)
301
    {
302
        /** @var Collection\FileCollectionRegistry $registry */
303
        $registry = GeneralUtility::makeInstance(FileCollectionRegistry::class);
304
305
        /** @var \TYPO3\CMS\Core\Collection\AbstractRecordCollection $class */
306
        $class = $registry->getFileCollectionClass($collectionData['type']);
307
308
        return $class::create($collectionData);
309
    }
310
311
    /**
312
     * Creates a storage object from a storage database row.
313
     *
314
     * @param array $storageRecord
315
     * @param array $storageConfiguration Storage configuration (if given, this won't be extracted from the FlexForm value but the supplied array used instead)
316
     * @return ResourceStorage
317
     */
318
    public function createStorageObject(array $storageRecord, array $storageConfiguration = null)
319
    {
320
        if (!$storageConfiguration) {
321
            $storageConfiguration = $this->convertFlexFormDataToConfigurationArray($storageRecord['configuration']);
322
        }
323
        $driverType = $storageRecord['driver'];
324
        $driverObject = $this->getDriverObject($driverType, $storageConfiguration);
325
        return GeneralUtility::makeInstance(ResourceStorage::class, $driverObject, $storageRecord, $this->eventDispatcher);
326
    }
327
328
    /**
329
     * Creates a folder to directly access (a part of) a storage.
330
     *
331
     * @param ResourceStorage $storage The storage the folder belongs to
332
     * @param string $identifier The path to the folder. Might also be a simple unique string, depending on the storage driver.
333
     * @param string $name The name of the folder (e.g. the folder name)
334
     * @return Folder
335
     */
336
    public function createFolderObject(ResourceStorage $storage, $identifier, $name)
337
    {
338
        return GeneralUtility::makeInstance(Folder::class, $storage, $identifier, $name);
339
    }
340
341
    /**
342
     * Creates an instance of the file given UID. The $fileData can be supplied
343
     * to increase performance.
344
     *
345
     * @param int $uid The uid of the file to instantiate.
346
     * @param array $fileData The record row from database.
347
     *
348
     * @throws \InvalidArgumentException
349
     * @throws Exception\FileDoesNotExistException
350
     * @return File
351
     */
352
    public function getFileObject($uid, array $fileData = [])
353
    {
354
        if (!is_numeric($uid)) {
0 ignored issues
show
introduced by
The condition is_numeric($uid) is always true.
Loading history...
355
            throw new \InvalidArgumentException('The UID of file has to be numeric. UID given: "' . $uid . '"', 1300096564);
356
        }
357
        if (empty($this->fileInstances[$uid])) {
358
            // Fetches data in case $fileData is empty
359
            if (empty($fileData)) {
360
                $fileData = $this->getFileIndexRepository()->findOneByUid($uid);
361
                if ($fileData === false) {
362
                    throw new FileDoesNotExistException('No file found for given UID: ' . $uid, 1317178604);
363
                }
364
            }
365
            $this->fileInstances[$uid] = $this->createFileObject($fileData);
366
        }
367
        return $this->fileInstances[$uid];
368
    }
369
370
    /**
371
     * Gets a file object from an identifier [storage]:[fileId]
372
     *
373
     * @param string $identifier
374
     * @return File|ProcessedFile|null
375
     * @throws \InvalidArgumentException
376
     */
377
    public function getFileObjectFromCombinedIdentifier($identifier)
378
    {
379
        if (!is_string($identifier) || $identifier === '') {
0 ignored issues
show
introduced by
The condition is_string($identifier) is always true.
Loading history...
380
            throw new \InvalidArgumentException('Invalid file identifier given. It must be of type string and not empty. "' . gettype($identifier) . '" given.', 1401732564);
381
        }
382
        $parts = GeneralUtility::trimExplode(':', $identifier);
383
        if (count($parts) === 2) {
384
            $storageUid = $parts[0];
385
            $fileIdentifier = $parts[1];
386
        } else {
387
            // We only got a path: Go into backwards compatibility mode and
388
            // use virtual Storage (uid=0)
389
            $storageUid = 0;
390
            $fileIdentifier = $parts[0];
391
        }
392
393
        // please note that getStorageObject() might modify $fileIdentifier when
394
        // auto-detecting the best-matching storage to use
395
        return $this->getFileObjectByStorageAndIdentifier($storageUid, $fileIdentifier);
0 ignored issues
show
Bug introduced by
It seems like $storageUid can also be of type string; however, parameter $storageUid of TYPO3\CMS\Core\Resource\...yStorageAndIdentifier() 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

395
        return $this->getFileObjectByStorageAndIdentifier(/** @scrutinizer ignore-type */ $storageUid, $fileIdentifier);
Loading history...
396
    }
397
398
    /**
399
     * Gets a file object from storage by file identifier
400
     * If the file is outside of the process folder, it gets indexed and returned as file object afterwards
401
     * If the file is within processing folder, the file object will be directly returned
402
     *
403
     * @param int $storageUid
404
     * @param string $fileIdentifier
405
     * @return File|ProcessedFile|null
406
     */
407
    public function getFileObjectByStorageAndIdentifier($storageUid, &$fileIdentifier)
408
    {
409
        $storage = $this->getStorageObject($storageUid, [], $fileIdentifier);
410
        if (!$storage->isWithinProcessingFolder($fileIdentifier)) {
411
            $fileData = $this->getFileIndexRepository()->findOneByStorageUidAndIdentifier($storage->getUid(), $fileIdentifier);
412
            if ($fileData === false) {
413
                $fileObject = $this->getIndexer($storage)->createIndexEntry($fileIdentifier);
414
            } else {
415
                $fileObject = $this->getFileObject($fileData['uid'], $fileData);
416
            }
417
        } else {
418
            $fileObject = $this->getProcessedFileRepository()->findByStorageAndIdentifier($storage, $fileIdentifier);
419
        }
420
421
        return $fileObject;
422
    }
423
424
    /**
425
     * Bulk function, can be used for anything to get a file or folder
426
     *
427
     * 1. It's a UID
428
     * 2. It's a combined identifier
429
     * 3. It's just a path/filename (coming from the oldstyle/backwards compatibility)
430
     *
431
     * Files, previously laid on fileadmin/ or something, will be "mapped" to the storage the file is
432
     * in now. Files like typo3temp/ or typo3conf/ will be moved to the first writable storage
433
     * in its processing folder
434
     *
435
     * $input could be
436
     * - "2:myfolder/myfile.jpg" (combined identifier)
437
     * - "23" (file UID)
438
     * - "uploads/myfile.png" (backwards-compatibility, storage "0")
439
     * - "file:23"
440
     *
441
     * @param string $input
442
     * @return File|Folder|null
443
     */
444
    public function retrieveFileOrFolderObject($input)
445
    {
446
        // Remove Environment::getPublicPath() because absolute paths under Windows systems contain ':'
447
        // This is done in all considered sub functions anyway
448
        $input = str_replace(Environment::getPublicPath() . '/', '', $input);
449
450
        if (GeneralUtility::isFirstPartOfStr($input, 'file:')) {
451
            $input = substr($input, 5);
452
            return $this->retrieveFileOrFolderObject($input);
453
        }
454
        if (MathUtility::canBeInterpretedAsInteger($input)) {
455
            return $this->getFileObject($input);
0 ignored issues
show
Bug introduced by
$input of type string is incompatible with the type integer expected by parameter $uid of TYPO3\CMS\Core\Resource\...actory::getFileObject(). ( Ignorable by Annotation )

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

455
            return $this->getFileObject(/** @scrutinizer ignore-type */ $input);
Loading history...
456
        }
457
        if (strpos($input, ':') > 0) {
458
            [$prefix] = explode(':', $input);
459
            if (MathUtility::canBeInterpretedAsInteger($prefix)) {
460
                // path or folder in a valid storageUID
461
                return $this->getObjectFromCombinedIdentifier($input);
462
            }
463
            if ($prefix === 'EXT') {
464
                $input = GeneralUtility::getFileAbsFileName($input);
465
                if (empty($input)) {
466
                    return null;
467
                }
468
469
                $input = PathUtility::getRelativePath(Environment::getPublicPath() . '/', PathUtility::dirname($input)) . PathUtility::basename($input);
470
                return $this->getFileObjectFromCombinedIdentifier($input);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getFileObj...binedIdentifier($input) also could return the type TYPO3\CMS\Core\Resource\ProcessedFile which is incompatible with the documented return type TYPO3\CMS\Core\Resource\...re\Resource\Folder|null.
Loading history...
471
            }
472
            return null;
473
        }
474
        // this is a backwards-compatible way to access "0-storage" files or folders
475
        // eliminate double slashes, /./ and /../
476
        $input = PathUtility::getCanonicalPath(ltrim($input, '/'));
477
        if (@is_file(Environment::getPublicPath() . '/' . $input)) {
478
            // only the local file
479
            return $this->getFileObjectFromCombinedIdentifier($input);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getFileObj...binedIdentifier($input) also could return the type TYPO3\CMS\Core\Resource\ProcessedFile which is incompatible with the documented return type TYPO3\CMS\Core\Resource\...re\Resource\Folder|null.
Loading history...
480
        }
481
        // only the local path
482
        return $this->getFolderObjectFromCombinedIdentifier($input);
483
    }
484
485
    /**
486
     * Gets a folder object from an identifier [storage]:[fileId]
487
     *
488
     * @TODO check naming, inserted by SteffenR while working on filelist
489
     * @param string $identifier
490
     * @return Folder
491
     */
492
    public function getFolderObjectFromCombinedIdentifier($identifier)
493
    {
494
        $parts = GeneralUtility::trimExplode(':', $identifier);
495
        if (count($parts) === 2) {
496
            $storageUid = $parts[0];
497
            $folderIdentifier = $parts[1];
498
        } else {
499
            // We only got a path: Go into backwards compatibility mode and
500
            // use virtual Storage (uid=0)
501
            $storageUid = 0;
502
503
            // please note that getStorageObject() might modify $folderIdentifier when
504
            // auto-detecting the best-matching storage to use
505
            $folderIdentifier = $parts[0];
506
            // make sure to not use an absolute path, and remove Environment::getPublicPath if it is prepended
507
            if (GeneralUtility::isFirstPartOfStr($folderIdentifier, Environment::getPublicPath() . '/')) {
508
                $folderIdentifier = PathUtility::stripPathSitePrefix($parts[0]);
509
            }
510
        }
511
        return $this->getStorageObject($storageUid, [], $folderIdentifier)->getFolder($folderIdentifier);
0 ignored issues
show
Bug introduced by
It seems like $storageUid can also be of type string; however, parameter $uid of TYPO3\CMS\Core\Resource\...ory::getStorageObject() 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

511
        return $this->getStorageObject(/** @scrutinizer ignore-type */ $storageUid, [], $folderIdentifier)->getFolder($folderIdentifier);
Loading history...
512
    }
513
514
    /**
515
     * Gets a storage object from a combined identifier
516
     *
517
     * @param string $identifier An identifier of the form [storage uid]:[object identifier]
518
     * @return ResourceStorage
519
     */
520
    public function getStorageObjectFromCombinedIdentifier($identifier)
521
    {
522
        $parts = GeneralUtility::trimExplode(':', $identifier);
523
        $storageUid = count($parts) === 2 ? $parts[0] : null;
524
        return $this->getStorageObject($storageUid);
0 ignored issues
show
Bug introduced by
It seems like $storageUid can also be of type string; however, parameter $uid of TYPO3\CMS\Core\Resource\...ory::getStorageObject() 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

524
        return $this->getStorageObject(/** @scrutinizer ignore-type */ $storageUid);
Loading history...
525
    }
526
527
    /**
528
     * Gets a file or folder object.
529
     *
530
     * @param string $identifier
531
     *
532
     * @throws Exception\ResourceDoesNotExistException
533
     * @return FileInterface|Folder
534
     */
535
    public function getObjectFromCombinedIdentifier($identifier)
536
    {
537
        [$storageId, $objectIdentifier] = GeneralUtility::trimExplode(':', $identifier);
538
        $storage = $this->getStorageObject($storageId);
0 ignored issues
show
Bug introduced by
$storageId of type string is incompatible with the type integer expected by parameter $uid of TYPO3\CMS\Core\Resource\...ory::getStorageObject(). ( Ignorable by Annotation )

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

538
        $storage = $this->getStorageObject(/** @scrutinizer ignore-type */ $storageId);
Loading history...
539
        if ($storage->hasFile($objectIdentifier)) {
540
            return $storage->getFile($objectIdentifier);
541
        }
542
        if ($storage->hasFolder($objectIdentifier)) {
543
            return $storage->getFolder($objectIdentifier);
544
        }
545
        throw new ResourceDoesNotExistException('Object with identifier "' . $identifier . '" does not exist in storage', 1329647780);
546
    }
547
548
    /**
549
     * Creates a file object from an array of file data. Requires a database
550
     * row to be fetched.
551
     *
552
     * @param array $fileData
553
     * @param ResourceStorage $storage
554
     * @return File
555
     */
556
    public function createFileObject(array $fileData, ResourceStorage $storage = null)
557
    {
558
        if (array_key_exists('storage', $fileData) && MathUtility::canBeInterpretedAsInteger($fileData['storage'])) {
559
            $storageObject = $this->getStorageObject((int)$fileData['storage']);
560
        } elseif ($storage !== null) {
561
            $storageObject = $storage;
562
            $fileData['storage'] = $storage->getUid();
563
        } else {
564
            throw new \RuntimeException('A file needs to reside in a Storage', 1381570997);
565
        }
566
        /** @var File $fileObject */
567
        $fileObject = GeneralUtility::makeInstance(File::class, $fileData, $storageObject);
568
        return $fileObject;
569
    }
570
571
    /**
572
     * Creates an instance of a FileReference object. The $fileReferenceData can
573
     * be supplied to increase performance.
574
     *
575
     * @param int $uid The uid of the file usage (sys_file_reference) to instantiate.
576
     * @param array $fileReferenceData The record row from database.
577
     * @param bool $raw Whether to get raw results without performing overlays
578
     * @return FileReference
579
     * @throws \InvalidArgumentException
580
     * @throws Exception\ResourceDoesNotExistException
581
     */
582
    public function getFileReferenceObject($uid, array $fileReferenceData = [], $raw = false)
583
    {
584
        if (!is_numeric($uid)) {
0 ignored issues
show
introduced by
The condition is_numeric($uid) is always true.
Loading history...
585
            throw new \InvalidArgumentException(
586
                'The reference UID for the file (sys_file_reference) has to be numeric. UID given: "' . $uid . '"',
587
                1300086584
588
            );
589
        }
590
        if (!$this->fileReferenceInstances[$uid]) {
591
            // Fetches data in case $fileData is empty
592
            if (empty($fileReferenceData)) {
593
                $fileReferenceData = $this->getFileReferenceData($uid, $raw);
594
                if (!is_array($fileReferenceData)) {
595
                    throw new ResourceDoesNotExistException(
596
                        'No file reference (sys_file_reference) was found for given UID: "' . $uid . '"',
597
                        1317178794
598
                    );
599
                }
600
            }
601
            $this->fileReferenceInstances[$uid] = $this->createFileReferenceObject($fileReferenceData);
602
        }
603
        return $this->fileReferenceInstances[$uid];
604
    }
605
606
    /**
607
     * Creates a file usage object from an array of fileReference data
608
     * from sys_file_reference table.
609
     * Requires a database row to be already fetched and present.
610
     *
611
     * @param array $fileReferenceData
612
     * @return FileReference
613
     */
614
    public function createFileReferenceObject(array $fileReferenceData)
615
    {
616
        /** @var FileReference $fileReferenceObject */
617
        $fileReferenceObject = GeneralUtility::makeInstance(FileReference::class, $fileReferenceData);
618
        return $fileReferenceObject;
619
    }
620
621
    /**
622
     * Gets data for the given uid of the file reference record.
623
     *
624
     * @param int $uid The uid of the file usage (sys_file_reference) to be fetched
625
     * @param bool $raw Whether to get raw results without performing overlays
626
     * @return array|null
627
     */
628
    protected function getFileReferenceData($uid, $raw = false)
629
    {
630
        if (!$raw && TYPO3_MODE === 'BE') {
631
            $fileReferenceData = BackendUtility::getRecordWSOL('sys_file_reference', $uid);
632
        } elseif (!$raw && is_object($GLOBALS['TSFE'])) {
633
            $fileReferenceData = $GLOBALS['TSFE']->sys_page->checkRecord('sys_file_reference', $uid);
634
        } else {
635
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_file_reference');
636
            $queryBuilder->getRestrictions()->removeAll()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
637
            $fileReferenceData = $queryBuilder->select('*')
638
                ->from('sys_file_reference')
639
                ->where(
640
                    $queryBuilder->expr()->eq(
641
                        'uid',
642
                        $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
643
                    )
644
                )
645
                ->execute()
646
                ->fetch();
647
        }
648
        return $fileReferenceData;
649
    }
650
651
    /**
652
     * Returns an instance of the FileIndexRepository
653
     *
654
     * @return FileIndexRepository
655
     */
656
    protected function getFileIndexRepository()
657
    {
658
        return FileIndexRepository::getInstance();
659
    }
660
661
    /**
662
     * Returns an instance of the ProcessedFileRepository
663
     *
664
     * @return ProcessedFileRepository
665
     */
666
    protected function getProcessedFileRepository()
667
    {
668
        return GeneralUtility::makeInstance(ProcessedFileRepository::class);
669
    }
670
671
    /**
672
     * Returns an instance of the Indexer
673
     *
674
     * @param ResourceStorage $storage
675
     * @return Index\Indexer
676
     */
677
    protected function getIndexer(ResourceStorage $storage)
678
    {
679
        return GeneralUtility::makeInstance(Indexer::class, $storage);
680
    }
681
}
682