ldc-legaulois/app/Http/Middleware/HtmlSanitizer.php

61 lines
1.8 KiB
PHP
Raw Permalink Normal View History

2024-01-10 14:49:46 +01:00
<?php
namespace App\Http\Middleware;
use App\Lib\Helpers\ToolboxHelper;
use Illuminate\Http\Request;
2026-09-25 16:25:31 +02:00
use Symfony\Component\HttpFoundation\Response;
2024-01-10 14:49:46 +01:00
class HtmlSanitizer
{
/**
* Handle an incoming request.
*/
public function handle(
Request $request,
\Closure $next,
2026-09-25 16:25:31 +02:00
string | array ...$params
): Response {
2024-01-10 14:49:46 +01:00
$inputs = $request->all();
/** @var callable|null */
$cleanInput = null;
$cleanInput = function (
2026-09-25 16:25:31 +02:00
null | string | array &$input,
2024-01-10 14:49:46 +01:00
string $name,
?string $rootName = null
) use (
$params,
&$cleanInput
): void {
// * Nested element array
if (is_array($input)) {
array_walk_recursive($input, $cleanInput, $name);
}
2026-09-25 16:25:31 +02:00
if (! is_string($input)) {
2024-01-10 14:49:46 +01:00
return;
}
if (in_array($name, $params) or in_array($rootName ?? $name, $params)) {
// ? Is a json input ?
if ($isJson = \json_decode($input, true) and is_array($isJson)) {
// ! Decode each json field recursive.
2026-09-25 16:25:31 +02:00
\array_walk_recursive($isJson, function (string | array &$item) {
2024-01-10 14:49:46 +01:00
if (\is_string($item)) {
$item = clean($item);
$item = ToolboxHelper::stripCkEditorSchemesOnMediaInputs($item);
}
});
} else {
$input = clean($input);
$input = ToolboxHelper::stripCkEditorSchemesOnMediaInputs($input);
}
} else {
$input = strip_tags($input);
}
};
\array_walk($inputs, $cleanInput);
$request->merge($inputs);
2026-09-25 16:25:31 +02:00
2024-01-10 14:49:46 +01:00
return $next($request);
}
}