|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace wcf\data; |
| 4 | + |
| 5 | +use wcf\data\file\FileList; |
| 6 | +use wcf\data\file\thumbnail\FileThumbnailList; |
| 7 | +use wcf\system\image\cover\photo\FileCoverPhoto; |
| 8 | + |
| 9 | +/** |
| 10 | + * Trait for dbo collections with cover photos. |
| 11 | + * |
| 12 | + * @author Marcel Werk |
| 13 | + * @copyright 2001-2025 WoltLab GmbH |
| 14 | + * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> |
| 15 | + * @since 6.3 |
| 16 | + */ |
| 17 | +trait TCollectionCoverPhotos |
| 18 | +{ |
| 19 | + /** |
| 20 | + * @var array<int, FileCoverPhoto> |
| 21 | + */ |
| 22 | + private array $coverPhotos; |
| 23 | + |
| 24 | + public function getCoverPhoto( |
| 25 | + DatabaseObject $object, |
| 26 | + string $coverPhotoIdProperty = 'coverPhotoFileID', |
| 27 | + ): ?FileCoverPhoto { |
| 28 | + $this->loadCoverPhotos($coverPhotoIdProperty); |
| 29 | + |
| 30 | + return $this->coverPhotos[$object->{$coverPhotoIdProperty}] ?? null; |
| 31 | + } |
| 32 | + |
| 33 | + private function loadCoverPhotos(string $coverPhotoIdProperty): void |
| 34 | + { |
| 35 | + if (isset($this->coverPhotos)) { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + $this->coverPhotos = []; |
| 40 | + $coverPhotoIDs = $this->getCoverPhotoIDs($coverPhotoIdProperty); |
| 41 | + if ($coverPhotoIDs === []) { |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + $fileList = new FileList(); |
| 46 | + $fileList->setObjectIDs($coverPhotoIDs); |
| 47 | + $fileList->readObjects(); |
| 48 | + $files = $fileList->getObjects(); |
| 49 | + |
| 50 | + $thumbnailList = new FileThumbnailList(); |
| 51 | + $thumbnailList->getConditionBuilder()->add("fileID IN (?)", [$fileList->getObjectIDs()]); |
| 52 | + $thumbnailList->readObjects(); |
| 53 | + foreach ($thumbnailList as $thumbnail) { |
| 54 | + $files[$thumbnail->fileID]->addThumbnail($thumbnail); |
| 55 | + } |
| 56 | + |
| 57 | + $this->coverPhotos = \array_map(fn($file) => new FileCoverPhoto($file), $files); |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * @return int[] |
| 62 | + */ |
| 63 | + private function getCoverPhotoIDs(string $coverPhotoIdProperty): array |
| 64 | + { |
| 65 | + \assert($this instanceof DatabaseObjectCollection); |
| 66 | + |
| 67 | + return \array_map( |
| 68 | + static fn(DatabaseObject $object) => $object->{$coverPhotoIdProperty}, |
| 69 | + \array_filter($this->getObjects(), static fn(DatabaseObject $object) => $object->{$coverPhotoIdProperty} !== null) |
| 70 | + ); |
| 71 | + } |
| 72 | +} |
0 commit comments