59 خطوط
1.8 KiB
PHP
59 خطوط
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
use App\Models\Setting;
|
|
use Closure;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
class MaskPhoneNumber
|
|
{
|
|
public function handle(Request $request, Closure $next): Response
|
|
{
|
|
$response = $next($request);
|
|
|
|
if (!$response instanceof JsonResponse) {
|
|
return $response;
|
|
}
|
|
|
|
$user = auth()->user();
|
|
$maskPhones = Setting::where('key', 'phone_mask_enabled')->value('value') !== 'false'
|
|
&& (!$user || !$user->can('view_full_phone'));
|
|
$maskRecordings = !$user || (!$user->hasRole('admin') && !$user->can('listen_recordings'));
|
|
|
|
if ($maskPhones || $maskRecordings) {
|
|
$data = $response->getData(true);
|
|
if (is_array($data)) {
|
|
$this->maskInArray($data, $maskPhones, $maskRecordings);
|
|
$response->setData($data);
|
|
}
|
|
}
|
|
|
|
return $response;
|
|
}
|
|
|
|
private function maskInArray(array &$data, bool $maskPhones, bool $maskRecordings): void
|
|
{
|
|
foreach ($data as $key => &$value) {
|
|
if ($maskPhones && in_array($key, ['phone', 'phone_secondary'], true) && is_string($value)) {
|
|
$value = $this->mask($value);
|
|
} elseif ($maskRecordings && in_array($key, ['recording_url', 'recordingUrl'], true)) {
|
|
$value = null;
|
|
} elseif (is_array($value)) {
|
|
$this->maskInArray($value, $maskPhones, $maskRecordings);
|
|
}
|
|
}
|
|
}
|
|
|
|
private function mask(string $phone): string
|
|
{
|
|
if (Setting::where('key', 'phone_mask_level')->value('value') === 'full') {
|
|
return '********';
|
|
}
|
|
if (strlen($phone) < 7) return $phone;
|
|
return substr($phone, 0, 4) . ' *** **' . substr($phone, -2);
|
|
}
|
|
}
|