Created
May 22, 2023 06:42
-
-
Save arfar-x/7ef53b34b2a0b4bf6792c9972db48e34 to your computer and use it in GitHub Desktop.
Normalize Persian and Arabic numbers to English in Laravel Middleware
This file contains hidden or 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\Http\Middleware; | |
| use Closure; | |
| use Illuminate\Http\RedirectResponse; | |
| use Illuminate\Http\Request; | |
| use Illuminate\Http\Response; | |
| class NormalizeNumbersMiddleware | |
| { | |
| /** | |
| * Handle an incoming request. | |
| * | |
| * @param Request $request | |
| * @param Closure $next | |
| * @return RedirectResponse|Response|mixed | |
| */ | |
| public function handle(Request $request, Closure $next) | |
| { | |
| $array = $request->all(); | |
| $request->merge($this->normalizeNumbers($array)); | |
| return $next($request); | |
| } | |
| /** | |
| * Normalize numbers (with string type) recursively. | |
| * | |
| * @param array& $fields | |
| * return array | |
| */ | |
| private function normalizeNumbers(array &$fields): array | |
| { | |
| foreach ($fields as $key => &$value) { | |
| if (is_array($value)) { | |
| $value = $this->normalizeNumbers($value); | |
| } elseif (!is_integer($value) && $this->isNumeric($value)) { | |
| $fields[$key] = $this->toEnglish($value); | |
| } | |
| } | |
| return $fields; | |
| } | |
| /** | |
| * Detect if string is a number (Persian, Arabic or English) | |
| * | |
| * @param $string | |
| * @return bool|int | |
| */ | |
| private function isNumeric($string): bool|int | |
| { | |
| // Numbers between [۰ - ۹] (Persian) or [٩ - ٠] (Arabic) or [0 - 9] | |
| return preg_match("/^([\x{6F0}-\x{6F9}|\x{660}-\x{669}0-9])+$/iu", $string); | |
| } | |
| private function toEnglish($string): array|string | |
| { | |
| $numbers = array( | |
| '٠' => '0', '۰' => '0', '١' => '1', '۱' => '1', '٢' => '2', | |
| '۲' => '2', '٣' => '3', '۳' => '3', '٤' => '4', '۴' => '4', | |
| '٥' => '5', '۵' => '5', '٦' => '6', '۶' => '6', '٧' => '7', | |
| '۷' => '7', '٨' => '8', '۸' => '8', '٩' => '9', '۹' => '9' | |
| ); | |
| return str_replace(array_keys($numbers), array_values($numbers), $string); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment