UploadFilesAction.php
87 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\Form\LegacyConsumer\Actions; |
| 4 | |
| 5 | use Give\Form\LegacyConsumer\Traits\HasFilesArray; |
| 6 | use Give\Framework\FieldsAPI\File; |
| 7 | |
| 8 | use function wp_check_filetype; |
| 9 | use function wp_generate_attachment_metadata; |
| 10 | use function wp_handle_upload; |
| 11 | use function wp_insert_attachment; |
| 12 | use function wp_update_attachment_metadata; |
| 13 | |
| 14 | /** |
| 15 | * @package Give\Form\LegacyConsumer\Commands |
| 16 | * |
| 17 | * @since 2.14.0 |
| 18 | */ |
| 19 | class UploadFilesAction |
| 20 | { |
| 21 | use HasFilesArray; |
| 22 | |
| 23 | /** |
| 24 | * @var array |
| 25 | */ |
| 26 | private $files; |
| 27 | |
| 28 | /** |
| 29 | * @var File |
| 30 | */ |
| 31 | private $field; |
| 32 | |
| 33 | /** |
| 34 | * @since 2.14.0 |
| 35 | */ |
| 36 | public function __construct(File $field) |
| 37 | { |
| 38 | $this->field = $field; |
| 39 | $this->files = $this->getFiles(); |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * @since 2.14.0 |
| 44 | */ |
| 45 | public function __invoke() |
| 46 | { |
| 47 | if ( ! function_exists('wp_handle_upload')) { |
| 48 | require_once(ABSPATH . 'wp-admin/includes/file.php'); |
| 49 | } |
| 50 | |
| 51 | $fileIds = []; |
| 52 | foreach ($this->files as $file) { |
| 53 | $upload = wp_handle_upload($file, ['test_form' => false,]); |
| 54 | |
| 55 | if (isset($upload['url'])) { |
| 56 | $path = $upload['url']; |
| 57 | |
| 58 | // Check the type of file. We'll use this as the 'post_mime_type'. |
| 59 | $filetype = wp_check_filetype(basename($path), null); |
| 60 | |
| 61 | // Prepare an array of post data for the attachment. |
| 62 | $attachment = [ |
| 63 | 'guid' => $path, |
| 64 | 'post_mime_type' => $filetype['type'], |
| 65 | 'post_title' => preg_replace('/\.[^.]+$/', '', basename($path)), |
| 66 | 'post_content' => '', |
| 67 | 'post_status' => 'inherit', |
| 68 | ]; |
| 69 | |
| 70 | // Insert the attachment. |
| 71 | $attachmentId = wp_insert_attachment($attachment, $path); |
| 72 | |
| 73 | // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. |
| 74 | require_once(ABSPATH . 'wp-admin/includes/image.php'); |
| 75 | |
| 76 | // Generate the metadata for the attachment, and update the database record. |
| 77 | $attachmentData = wp_generate_attachment_metadata($attachmentId, $path); |
| 78 | wp_update_attachment_metadata($attachmentId, $attachmentData); |
| 79 | |
| 80 | $fileIds[] = $attachmentId; |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | return $fileIds; |
| 85 | } |
| 86 | } |
| 87 |