Attachments.php
2 days ago
Author.php
2 days ago
BeforeMoreContent.php
2 days ago
CommentCount.php
2 days ago
CommentsForPostLink.php
2 days ago
ContentExcerpt.php
2 days ago
DatePublishFormatted.php
2 days ago
Depth.php
2 days ago
DescriptivePostStatus.php
2 days ago
DiscussionStatus.php
2 days ago
Excerpt.php
2 days ago
ExcerptMissingMessage.php
2 days ago
ExcerptRaw.php
2 days ago
FeaturedImage.php
2 days ago
HasCommentStatus.php
2 days ago
IsPasswordProtected.php
2 days ago
IsSticky.php
2 days ago
LastModifiedAuthor.php
2 days ago
Meta.php
2 days ago
ModifiedDate.php
2 days ago
Order.php
2 days ago
PageTemplate.php
2 days ago
Path.php
2 days ago
Permalink.php
2 days ago
PingStatus.php
2 days ago
PostContent.php
2 days ago
PostDate.php
2 days ago
PostDateTimestamp.php
2 days ago
PostFormat.php
2 days ago
PostFormatIcon.php
2 days ago
PostFormatLabel.php
2 days ago
PostLink.php
2 days ago
PostParentId.php
2 days ago
PostReferences.php
2 days ago
PostStatus.php
2 days ago
PostStatusIcon.php
2 days ago
PostTerms.php
2 days ago
PostTermsOriginal.php
2 days ago
PostTitle.php
2 days ago
Property.php
2 days ago
ShortLink.php
2 days ago
Shortcodes.php
2 days ago
Slug.php
2 days ago
Attachments.php
54 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace AC\Formatter\Post; |
| 6 | |
| 7 | use AC\Exception\ValueNotFoundException; |
| 8 | use AC\Formatter; |
| 9 | use AC\Type\Value; |
| 10 | use AC\Type\ValueCollection; |
| 11 | |
| 12 | class Attachments implements Formatter |
| 13 | { |
| 14 | public function format(Value $value): ValueCollection |
| 15 | { |
| 16 | $parent_id = (int)$value->get_value(); |
| 17 | |
| 18 | if (! $parent_id) { |
| 19 | throw new ValueNotFoundException('Parent ID is required'); |
| 20 | } |
| 21 | |
| 22 | $attachment_ids = get_posts([ |
| 23 | 'post_type' => 'attachment', |
| 24 | 'posts_per_page' => -1, |
| 25 | 'post_status' => 'inherit', |
| 26 | 'post_parent' => $parent_id, |
| 27 | 'fields' => 'ids', |
| 28 | ]); |
| 29 | |
| 30 | return ValueCollection::from_ids($parent_id, $this->group_by_extension($attachment_ids)); |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Group attachment IDs by file extension, preserving the order of first appearance. |
| 35 | * |
| 36 | * @param int[] $ids |
| 37 | * @return int[] |
| 38 | */ |
| 39 | private function group_by_extension(array $ids): array |
| 40 | { |
| 41 | $groups = []; |
| 42 | |
| 43 | foreach ($ids as $id) { |
| 44 | $file = get_attached_file($id); |
| 45 | $ext = $file ? strtolower((string)pathinfo($file, PATHINFO_EXTENSION)) : ''; |
| 46 | |
| 47 | $groups[$ext][] = $id; |
| 48 | } |
| 49 | |
| 50 | return array_merge(...array_values($groups)); |
| 51 | } |
| 52 | |
| 53 | } |
| 54 |