MediaResource.php
69 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Kirki\App\Resources\Media; |
| 4 | |
| 5 | use Kirki\App\Constants\PostStatus; |
| 6 | use function Kirki\Framework\config; |
| 7 | |
| 8 | defined('ABSPATH') || exit; |
| 9 | |
| 10 | use Kirki\Framework\Resource; |
| 11 | |
| 12 | class MediaResource extends Resource |
| 13 | { |
| 14 | /** |
| 15 | * Convert the media resource to an array. |
| 16 | * |
| 17 | * @return array The media data as an associative array. |
| 18 | */ |
| 19 | public function to_array() |
| 20 | { |
| 21 | $categories = config('media.supports', []); |
| 22 | $category = ''; |
| 23 | |
| 24 | foreach ($categories as $type => $mime_types) { |
| 25 | if (in_array($this->post_mime_type, $mime_types, true)) { |
| 26 | $category = $type === 'svg' ? 'image' : $type; |
| 27 | break; |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | $meta = $this->mapped_meta(); |
| 32 | |
| 33 | $alt = $meta['_wp_attachment_image_alt'] ?? ''; |
| 34 | $file_path = $meta['_wp_attached_file'] ?? ''; |
| 35 | $file_meta = $meta['_wp_attachment_metadata'] ?? ''; |
| 36 | $file_size = $file_meta['filesize'] ?? 0; |
| 37 | $file_extension = $file_path ? pathinfo($file_path, PATHINFO_EXTENSION) : ''; |
| 38 | |
| 39 | return [ |
| 40 | 'id' => (int) $this->ID, |
| 41 | 'name' => $this->post_name, |
| 42 | 'alt' => $alt ? $alt : $this->post_title, |
| 43 | 'type' => $this->post_mime_type, |
| 44 | 'url' => $this->guid, |
| 45 | 'thumbnail' => wp_get_attachment_image_url($this->ID), |
| 46 | 'category' => $category, |
| 47 | 'trash' => PostStatus::TRASH === $this->post_status, |
| 48 | 'file_size' => size_format($file_size), |
| 49 | 'file_extension' => $file_extension, |
| 50 | ]; |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Map the item's meta as meta_key => meta_value. |
| 55 | * |
| 56 | * @return array<string, mixed> |
| 57 | */ |
| 58 | protected function mapped_meta() |
| 59 | { |
| 60 | $map = []; |
| 61 | |
| 62 | foreach ($this->meta ?? [] as $meta) { |
| 63 | $map[$meta->meta_key] = $meta->meta_value; |
| 64 | } |
| 65 | |
| 66 | return $map; |
| 67 | } |
| 68 | } |
| 69 |