|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace wcf\data; |
| 4 | + |
| 5 | +use wcf\data\attachment\Attachment; |
| 6 | +use wcf\data\attachment\GroupedAttachmentList; |
| 7 | + |
| 8 | +/** |
| 9 | + * Trait for dbo collections with attachments. |
| 10 | + * |
| 11 | + * @author Marcel Werk |
| 12 | + * @copyright 2001-2026 WoltLab GmbH |
| 13 | + * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> |
| 14 | + * @since 6.3 |
| 15 | + */ |
| 16 | +trait TCollectionAttachments |
| 17 | +{ |
| 18 | + private GroupedAttachmentList $attachments; |
| 19 | + |
| 20 | + /** |
| 21 | + * @return Attachment[] |
| 22 | + */ |
| 23 | + public function getAttachments(DatabaseObject $object): array |
| 24 | + { |
| 25 | + if (!$this->hasAttachments($object)) { |
| 26 | + return []; |
| 27 | + } |
| 28 | + |
| 29 | + $this->loadAttachments(); |
| 30 | + |
| 31 | + return $this->attachments->getGroupedObjects($object->getObjectID()); |
| 32 | + } |
| 33 | + |
| 34 | + private function loadAttachments(): void |
| 35 | + { |
| 36 | + if (isset($this->attachments)) { |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + $this->attachments = new GroupedAttachmentList($this->getAttachmentObjectType()); |
| 41 | + |
| 42 | + $objectIDs = $this->getAttachmentObjectIDs(); |
| 43 | + if ($objectIDs === []) { |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + $this->attachments->getConditionBuilder()->add('attachment.objectID IN (?)', [$objectIDs]); |
| 48 | + $this->attachments->readObjects(); |
| 49 | + $this->attachments->setPermissions($this->getAttachmentPermissions()); |
| 50 | + } |
| 51 | + |
| 52 | + protected abstract function getAttachmentObjectType(): string; |
| 53 | + |
| 54 | + /** |
| 55 | + * @return array<string, bool> |
| 56 | + */ |
| 57 | + protected function getAttachmentPermissions(): array |
| 58 | + { |
| 59 | + return [ |
| 60 | + 'canDownload' => true, |
| 61 | + 'canViewPreview' => true, |
| 62 | + ]; |
| 63 | + } |
| 64 | + |
| 65 | + protected function hasAttachments(DatabaseObject $object): bool |
| 66 | + { |
| 67 | + return $object->attachments > 0; |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * @return list<int> |
| 72 | + */ |
| 73 | + private function getAttachmentObjectIDs(): array |
| 74 | + { |
| 75 | + \assert($this instanceof DatabaseObjectCollection); |
| 76 | + |
| 77 | + return \array_map( |
| 78 | + static fn(DatabaseObject $object) => $object->getObjectID(), |
| 79 | + \array_filter($this->getObjects(), fn(DatabaseObject $object) => $this->hasAttachments($object)) |
| 80 | + ); |
| 81 | + } |
| 82 | +} |
0 commit comments