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