| 1 |
<?php |
| 2 |
namespace Depicter\WordPress; |
| 3 |
|
| 4 |
use Averta\WordPress\File\UploadsDirectory; |
| 5 |
use GuzzleHttp\Psr7\UploadedFile; |
| 6 |
|
| 7 |
class FileUploaderService |
| 8 |
{ |
| 9 |
public function upload( array $files ) { |
| 10 |
$results = []; |
| 11 |
$wp_upload_dir = new UploadsDirectory(); |
| 12 |
$allowedMimeTypes = array_values( get_allowed_mime_types() ); |
| 13 |
foreach( $files as $file ) { |
| 14 |
if ( ! $file instanceof UploadedFile ) { |
| 15 |
continue; |
| 16 |
} |
| 17 |
|
| 18 |
if ( $file->getError() ) { |
| 19 |
$results[ $file->getClientFilename() ] = [ |
| 20 |
'attachment' => 0, |
| 21 |
'errors' => [ |
| 22 |
sprintf( __( 'Cannot upload the file, because max permitted file upload size is %s.', 'depicter' ), ini_get('upload_max_filesize') ) |
| 23 |
] |
| 24 |
]; |
| 25 |
continue; |
| 26 |
} |
| 27 |
|
| 28 |
if ( !in_array( $file->getClientMediaType(), $allowedMimeTypes ) ) { |
| 29 |
$results[ $file->getClientFilename() ] = [ |
| 30 |
'attachment' => 0, |
| 31 |
'errors' => [ |
| 32 |
sprintf( __( 'Cannot upload the file, uploading %s files are not allowed.', 'depicter' ), $file->getClientMediaType() ) |
| 33 |
] |
| 34 |
]; |
| 35 |
continue; |
| 36 |
} |
| 37 |
|
| 38 |
$filename = $wp_upload_dir->getPath() . "/" . $file->getClientFilename(); |
| 39 |
$file->moveTo( $filename ); |
| 40 |
$attachment = array( |
| 41 |
'guid' => $wp_upload_dir->getUrl() . '/' . basename( $filename ), |
| 42 |
'post_mime_type' => $file->getClientMediaType(), |
| 43 |
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ), |
| 44 |
'post_content' => '', |
| 45 |
'post_status' => 'inherit' |
| 46 |
); |
| 47 |
|
| 48 |
$attach_id = wp_insert_attachment( $attachment, $filename ); |
| 49 |
|
| 50 |
if ( !is_wp_error( $attach_id ) ) { |
| 51 |
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. |
| 52 |
require_once( ABSPATH . 'wp-admin/includes/image.php' ); |
| 53 |
|
| 54 |
// Generate the metadata for the attachment, and update the database record. |
| 55 |
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename ); |
| 56 |
wp_update_attachment_metadata( $attach_id, $attach_data ); |
| 57 |
$results[ $file->getClientFilename() ] = [ |
| 58 |
'attachment' => $attach_id, |
| 59 |
'errors' => [] |
| 60 |
]; |
| 61 |
} else { |
| 62 |
$results[ $file->getClientFilename() ] = [ |
| 63 |
'attachment' => 0, |
| 64 |
'errors' => [ |
| 65 |
$attach_id['error'] |
| 66 |
] |
| 67 |
]; |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
return $results; |
| 72 |
} |
| 73 |
} |
| 74 |
|