| 1 |
<?php |
| 2 |
namespace Depicter\Controllers\Ajax; |
| 3 |
|
| 4 |
use Averta\Core\Utility\Arr; |
| 5 |
use GuzzleHttp\Psr7\UploadedFile; |
| 6 |
use WPEmerge\Requests\RequestInterface; |
| 7 |
|
| 8 |
class ImportAjaxController |
| 9 |
{ |
| 10 |
|
| 11 |
/** |
| 12 |
* @param RequestInterface $request |
| 13 |
* @param $view |
| 14 |
* |
| 15 |
* @return \Psr\Http\Message\ResponseInterface |
| 16 |
*/ |
| 17 |
public function unpack( RequestInterface $request, $view ) { |
| 18 |
$zipFile = $request->files('file'); |
| 19 |
|
| 20 |
if ( empty( $zipFile ) || ! $zipFile instanceof UploadedFile ) { |
| 21 |
return \Depicter::json([ |
| 22 |
'errors' => [ __( 'No file provided to upload', 'depicter')] |
| 23 |
])->withStatus(400 ); |
| 24 |
} |
| 25 |
|
| 26 |
if ( $zipFile->getError() ) { |
| 27 |
return \Depicter::json([ |
| 28 |
'errors' => [ |
| 29 |
/* translators: maximum file size allowed to upload */ |
| 30 |
sprintf( __( 'Cannot upload the file, because max permitted file upload size is %s.', 'depicter' ), ini_get('upload_max_filesize') ) |
| 31 |
] |
| 32 |
]); |
| 33 |
} |
| 34 |
|
| 35 |
$zipMediaTypes = [ |
| 36 |
'application/zip', |
| 37 |
'application/x-zip-compressed' |
| 38 |
]; |
| 39 |
if( !in_array( $zipFile->getClientMediaType(), $zipMediaTypes ) ){ |
| 40 |
return \Depicter::json([ |
| 41 |
'errors' => [ __( 'Provided file must be zip file.', 'depicter') ] |
| 42 |
])->withStatus(400 ); |
| 43 |
} |
| 44 |
|
| 45 |
$filename = $zipFile->getClientFilename(); |
| 46 |
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); |
| 47 |
|
| 48 |
if ($extension !== 'zip') { |
| 49 |
return \Depicter::json([ |
| 50 |
'errors' => [ __( 'Provided file must be zip file.', 'depicter') ] |
| 51 |
])->withStatus(400 ); |
| 52 |
} |
| 53 |
|
| 54 |
if ( ! class_exists('ZipArchive') ) { |
| 55 |
return \Depicter::json([ |
| 56 |
'errors' => [ __( 'To import slider you need to enable "php-zip" module on your server.', 'depicter')] |
| 57 |
])->withStatus(400 ); |
| 58 |
} |
| 59 |
|
| 60 |
$sliderID = \Depicter::importService()->unpack($zipFile); |
| 61 |
if ( $sliderID ) { |
| 62 |
$slider = \Depicter::documentRepository()->findById( $sliderID ); |
| 63 |
return \Depicter::json([ |
| 64 |
'success' => [ __( 'Slider imported successfully', 'depicter' ) ], |
| 65 |
'hits' => Arr::camelizeKeys( $slider->getProperties(), '_', [], true ) |
| 66 |
])->withStatus(200 ); |
| 67 |
} else { |
| 68 |
return \Depicter::json([ |
| 69 |
'errors' => [ __( 'Error occurred during import process.', 'depicter' )] |
| 70 |
])->withStatus(400 ); |
| 71 |
} |
| 72 |
} |
| 73 |
} |
| 74 |
|