Last active
June 2, 2024 06:43
-
-
Save vafrcor/e3414514adf112057f337344dacda084 to your computer and use it in GitHub Desktop.
Laravel Validator Extension for Image Data URI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Helper\ValidatorExtensions; | |
use Illuminate\Support\Facades\Validator; | |
/** | |
* Validator Extension registration on Laravel AppServiceProvider.php: | |
* => Validator::extend('is_base64_image_data', 'App\Helper\ValidatorExtensions\Base64DataUri@validate'); | |
* => Validator::replacer('is_base64_image_data', 'App\Helper\ValidatorExtensions\Base64DataUri@replacer'); | |
* Usage on Controller: | |
* => $validator = Validator::make($request->all(), ['image_uri' => 'required|string|is_base64_image_data:image/png,image/jpeg']); | |
* Laravel language translation (validation.php): | |
* => 'is_base64_image_data' => ':Attribute should be an image data URL which encoded using base64 (Allowed mime-type: :values)', | |
*/ | |
class Base64DataUri{ | |
public function validate($attribute, $value, $params, $validator) { | |
$allowed_mimetype = array_intersect($params, ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp', 'image/webp']); | |
$base64_header_format= "data:{mime};base64,"; | |
$data = null; | |
$image = null; | |
foreach($allowed_mimetype as $mime){ | |
$current_header_format = str_replace("{mime}", $mime, $base64_header_format); | |
if(strpos($value, $current_header_format) !== false){ | |
$data = str_replace($current_header_format, "", $value); | |
$data = str_replace(' ', '+', $data); | |
$image = base64_decode($data); | |
break; | |
} | |
} | |
if ($image == null) return false; | |
$f = finfo_open(); | |
$result = finfo_buffer($f, $image, FILEINFO_MIME_TYPE); | |
// Due to some server encoding issue, we need to keep `application/octet-stream` as valid mime-type | |
return in_array($result, array_merge(["application/octet-stream"], $allowed_mimetype)); | |
} | |
public function replacer ($message, $attribute, $rule, $params) { | |
return str_replace(':values', implode(', ', $params), $message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment