Files
boursecu_server/app/Http/Middleware/ValidationMiddleware.php
T

67 lines
2.5 KiB
PHP
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class ValidationMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if($request->acceptsJson()){
//convert fa digits to en digits
$allData = array_merge($request->all(), $request->query());
$converted = $this->fa2en_numbers($allData);
$request->merge($converted);
$method = $request->getMethod();
$path =$request->path();
if(preg_match('/[0-9]+$/',$request->path(),$match)) {
$match_id = $match[0];
$path = preg_replace('/[0-9]+$/', '{id}', $request->path());
}
$format = 'validation.'.$path.'@'.strtolower($method);
if (config($format)) {
if ($path == 'admin/user/{id}'){
$replace = preg_replace('/update_id/', $match_id, config($format));
$validator = Validator::make($request->all(), $replace);
}
// elseif(isset($match[0])){
// $replace = preg_replace('/update_#/', $match[0], config($format));
// $validator = Validator::make($request->all(), $replace);
// }
else{
$validator = Validator::make($request->all(), config($format));
}
if ($validator->fails()) {
return response()->json($validator->errors(),422);
}
}
return $next($request);
}
throw new BadRequestHttpException();
}
private function fa2en_numbers($input) {
if (is_string($input)) {
$fa_numbers = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
$en_numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
return str_replace($fa_numbers, $en_numbers, $input);
} elseif (is_array($input)) {
return array_map([$this, __FUNCTION__], $input);
} else {
return $input;
}
}
}