Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
71.43% covered (warning)
71.43%
20 / 28
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
HtmlSanitizer
71.43% covered (warning)
71.43%
20 / 28
0.00% covered (danger)
0.00%
0 / 1
9.49
0.00% covered (danger)
0.00%
0 / 1
 handle
71.43% covered (warning)
71.43%
20 / 28
0.00% covered (danger)
0.00%
0 / 1
9.49
1<?php
2
3namespace App\Http\Middleware;
4
5use App\Lib\Helpers\ToolboxHelper;
6use Illuminate\Http\Request;
7use Symfony\Component\HttpFoundation\Response;
8
9class HtmlSanitizer
10{
11    /**
12     * Handle an incoming request.
13     *
14     * @param  \Illuminate\Http\Request $request
15     * @param  \Closure                 $next
16     * @param  string|array             ...$params
17     * @return \Symfony\Component\HttpFoundation\Response
18     */
19    public function handle(Request $request, \Closure $next, string|array ...$params): Response
20    {
21        $inputs = $request->all();
22        /** @var callable|null */
23        $cleanInput = null;
24        $cleanInput = function (
25            null|string|array &$input,
26            string $name,
27            ?string $rootName = null
28        ) use (
29            $params,
30            &$cleanInput
31        ): void {
32            // * Nested element array
33            if (is_array($input)) {
34                array_walk_recursive($input, $cleanInput, $name);
35            }
36            if (!is_string($input)) {
37                return;
38            }
39            if (in_array($name, $params) or in_array($rootName ?? $name, $params)) {
40                // ? Is a json input ?
41                if ($isJson = \json_decode($input, true) and is_array($isJson)) {
42                    // ! Decode each json field recursive.
43                    \array_walk_recursive($isJson, function (string|array &$item) {
44                        if (\is_string($item)) {
45                            $item = clean($item);
46                            $item = ToolboxHelper::stripCkEditorSchemesOnMediaInputs($item);
47                        }
48                    });
49                } else {
50                    $input = clean($input);
51                    $input = ToolboxHelper::stripCkEditorSchemesOnMediaInputs($input);
52                }
53            } else {
54                $input = strip_tags($input);
55            }
56        };
57        \array_walk($inputs, $cleanInput);
58        $request->merge($inputs);
59        return $next($request);
60    }
61}