| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentSupport\App\Services; |
| 4 |
|
| 5 |
use Exception; |
| 6 |
use FluentSupport\App\Models\Agent; |
| 7 |
use FluentSupport\App\Models\Customer; |
| 8 |
use FluentSupport\App\Services\Includes\FileSystem; |
| 9 |
|
| 10 |
class AvatarUploder |
| 11 |
{ |
| 12 |
/** |
| 13 |
* @param $file - file object |
| 14 |
* @param int $userid - user id |
| 15 |
* @param string $type - Customer or Agent |
| 16 |
* @throws Exception |
| 17 |
* @return array |
| 18 |
*/ |
| 19 |
public function addOrUpdateProfileImage ( $file, $userid, $type ) |
| 20 |
{ |
| 21 |
$this->validateExtension($file); |
| 22 |
|
| 23 |
$user = $type == 'customer'? Customer::findOrFail($userid) : Agent::findOrFail($userid); |
| 24 |
|
| 25 |
$uploadedImage = FileSystem::setSubDir(strtolower($type).'_avatars')->put($file); |
| 26 |
|
| 27 |
|
| 28 |
if ( !$uploadedImage ) { |
| 29 |
throw new Exception(esc_html__('Something went wrong while updating the profile picture', 'fluent-support'), 403); |
| 30 |
} |
| 31 |
|
| 32 |
$user->avatar = $uploadedImage[0]['url']; |
| 33 |
$user->save(); |
| 34 |
|
| 35 |
return [ |
| 36 |
'message' => __('Profile picture has been updated successfully', 'fluent-support'), |
| 37 |
'image' => $user->avatar, |
| 38 |
$type => $user |
| 39 |
]; |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* This Method Will Validate The Extension Of The File |
| 44 |
* @param $file - file object |
| 45 |
* @throws Exception |
| 46 |
* @return bool |
| 47 |
*/ |
| 48 |
private function validateExtension($file) |
| 49 |
{ |
| 50 |
/** |
| 51 |
* Filter profile picture upload types |
| 52 |
* @param array $allowedExtension |
| 53 |
*/ |
| 54 |
$allowedExtension = apply_filters('fluent_support/allowed_customer_profile_picture_file_type', |
| 55 |
array('jpeg', 'jpe', 'jpg', 'png')); |
| 56 |
|
| 57 |
$ext = $file['file']->getClientOriginalExtension(); |
| 58 |
|
| 59 |
if( !in_array($ext, $allowedExtension) ) { |
| 60 |
throw new Exception( |
| 61 |
sprintf( |
| 62 |
// translators: %s is a comma-separated list of allowed file extensions (e.g., "jpg, png, gif") |
| 63 |
esc_html__('Unsupported file submitted, allowed image file types are: %s', 'fluent-support'), |
| 64 |
esc_html(implode(", ", $allowedExtension)) |
| 65 |
), 403 |
| 66 |
); |
| 67 |
} |
| 68 |
|
| 69 |
return true; |
| 70 |
} |
| 71 |
} |
| 72 |
|