MediaPreview.php
73 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace AC\Value\Extended; |
| 6 | |
| 7 | use AC\ApplyFilter\ValidAudioMimetypes; |
| 8 | use AC\ApplyFilter\ValidVideoMimetypes; |
| 9 | use AC\Column; |
| 10 | use AC\ListScreen; |
| 11 | use AC\Value\ExtendedValueLink; |
| 12 | use AC\View\Embed\Video; |
| 13 | |
| 14 | class MediaPreview implements ExtendedValue |
| 15 | { |
| 16 | private const NAME = 'media-preview'; |
| 17 | |
| 18 | public function get_link($id, string $label): ExtendedValueLink |
| 19 | { |
| 20 | return new ExtendedValueLink($label, $id, self::NAME); |
| 21 | } |
| 22 | |
| 23 | public function can_render(string $view): bool |
| 24 | { |
| 25 | return $view === self::NAME; |
| 26 | } |
| 27 | |
| 28 | private function get_media_type($id): ?string |
| 29 | { |
| 30 | $mime_type = get_post_field('post_mime_type', $id); |
| 31 | |
| 32 | switch (true) { |
| 33 | case in_array($mime_type, (new ValidVideoMimetypes())->apply_filters(), true): |
| 34 | return 'video'; |
| 35 | |
| 36 | case in_array($mime_type, (new ValidAudioMimetypes())->apply_filters(), true): |
| 37 | return 'audio'; |
| 38 | |
| 39 | case wp_get_attachment_image_src($id): |
| 40 | return 'image'; |
| 41 | |
| 42 | default: |
| 43 | return null; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | public function render($id, array $params, Column $column, ListScreen $list_screen): string |
| 48 | { |
| 49 | $url = wp_get_attachment_url($id); |
| 50 | |
| 51 | if ($url) { |
| 52 | switch ($this->get_media_type($id)) { |
| 53 | case 'audio': |
| 54 | return sprintf( |
| 55 | '<audio controls autoplay="autoplay" preload="none" src="%s">%s</audio>', |
| 56 | esc_url($url), |
| 57 | __('No support for audio player', 'codepress-admin-columns') |
| 58 | ); |
| 59 | case 'video': |
| 60 | return (new Video([])) |
| 61 | ->set_src($url) |
| 62 | ->render(); |
| 63 | |
| 64 | case 'image': |
| 65 | return sprintf('<img src="%s" alt="">', esc_url($url)); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | return __('Preview not available', 'codepress-admin-columns'); |
| 70 | } |
| 71 | |
| 72 | } |
| 73 |