| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* @copyright © Melograno Venture Studio. All rights reserved. |
| 5 |
* @licence See COPYING.md for license details. |
| 6 |
*/ |
| 7 |
|
| 8 |
declare(strict_types=1); |
| 9 |
|
| 10 |
namespace IvyForms\Services\Submission; |
| 11 |
|
| 12 |
/** |
| 13 |
* Registers uploaded files in the WordPress media library. |
| 14 |
*/ |
| 15 |
final class SubmissionUploadMediaRegistrar |
| 16 |
{ |
| 17 |
public static function register(string $file): string |
| 18 |
{ |
| 19 |
self::ensureMediaFunctionsLoaded(); |
| 20 |
|
| 21 |
$attachId = self::insertAttachment($file); |
| 22 |
if ($attachId === 0) { |
| 23 |
return ''; |
| 24 |
} |
| 25 |
|
| 26 |
self::generateMetadata($attachId, $file); |
| 27 |
|
| 28 |
return self::publicUrl($attachId); |
| 29 |
} |
| 30 |
|
| 31 |
private static function ensureMediaFunctionsLoaded(): void |
| 32 |
{ |
| 33 |
if (!function_exists('wp_insert_attachment')) { |
| 34 |
require_once ABSPATH . 'wp-admin/includes/media.php'; |
| 35 |
} |
| 36 |
if (!function_exists('wp_generate_attachment_metadata')) { |
| 37 |
require_once ABSPATH . 'wp-admin/includes/image.php'; |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
private static function insertAttachment(string $file): int |
| 42 |
{ |
| 43 |
$fileName = basename($file); |
| 44 |
$fileType = wp_check_filetype($fileName, null); |
| 45 |
$mime = is_array($fileType) && !empty($fileType['type']) ? $fileType['type'] : ''; |
| 46 |
$attachment = [ |
| 47 |
'post_mime_type' => $mime, |
| 48 |
'post_title' => preg_replace('/\.[^.]+$/', '', $fileName), |
| 49 |
'post_content' => '', |
| 50 |
'post_status' => 'inherit', |
| 51 |
]; |
| 52 |
/** @var int|\WP_Error $attachId */ |
| 53 |
$attachId = wp_insert_attachment($attachment, $file); |
| 54 |
if (is_wp_error($attachId) || !$attachId) { |
| 55 |
return 0; |
| 56 |
} |
| 57 |
|
| 58 |
return (int) $attachId; |
| 59 |
} |
| 60 |
|
| 61 |
private static function generateMetadata(int $attachId, string $file): void |
| 62 |
{ |
| 63 |
$meta = wp_generate_attachment_metadata($attachId, $file); |
| 64 |
if (is_array($meta) && $meta !== []) { |
| 65 |
wp_update_attachment_metadata($attachId, $meta); |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
private static function publicUrl(int $attachId): string |
| 70 |
{ |
| 71 |
$attachmentUrl = wp_get_attachment_url($attachId); |
| 72 |
|
| 73 |
return $attachmentUrl ? (string) $attachmentUrl : ''; |
| 74 |
} |
| 75 |
} |
| 76 |
|