ldc-gen-game-web/app/Http/Middleware/HtmlSanitizer.php

61 lines
1.9 KiB
PHP
Raw Permalink Normal View History

2023-08-21 10:22:07 +02:00
<?php
2026-10-02 12:09:46 +02:00
declare(strict_types=1);
2023-08-21 10:22:07 +02:00
namespace App\Http\Middleware;
use App\Lib\Helpers\ToolboxHelper;
2026-10-02 12:09:46 +02:00
use Closure;
2023-08-21 10:22:07 +02:00
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class HtmlSanitizer
{
/**
* Handle an incoming request.
*/
2026-10-02 12:09:46 +02:00
public function handle(Request $request, Closure $next, string | array ...$params): Response
2023-08-21 10:22:07 +02:00
{
$inputs = $request->all();
/** @var callable|null */
$cleanInput = null;
$cleanInput = function (
2026-10-02 12:09:46 +02:00
null | string | array &$input,
2023-08-21 10:22:07 +02:00
string $name,
?string $rootName = null
) use (
$params,
&$cleanInput
): void {
// * Nested element array
if (is_array($input)) {
array_walk_recursive($input, $cleanInput, $name);
}
2026-10-02 12:09:46 +02:00
if (! is_string($input)) {
2023-08-21 10:22:07 +02:00
return;
}
2026-10-02 12:09:46 +02:00
if (in_array($name, $params) || in_array($rootName ?? $name, $params)) {
2023-08-21 10:22:07 +02:00
// ? Is a json input ?
if ($isJson = \json_decode($input, true) and is_array($isJson)) {
// ! Decode each json field recursive.
2026-10-02 12:09:46 +02:00
\array_walk_recursive($isJson, function (string | array &$item): void {
2023-08-21 10:22:07 +02: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-10-02 12:09:46 +02:00
2023-08-21 10:22:07 +02:00
return $next($request);
}
}