Skip to content

Instantly share code, notes, and snippets.

@mglaman
Created January 10, 2023 15:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mglaman/4533051f0ec50ebd698bbde93c1ac79b to your computer and use it in GitHub Desktop.
Save mglaman/4533051f0ec50ebd698bbde93c1ac79b to your computer and use it in GitHub Desktop.
TrimMiddleware for Drupal
services:
http_middleware.trim:
class: Drupal\mymodule\StackMiddleware\TrimMiddleware
arguments: ['@kernel']
tags:
- { name: http_middleware }
<?php
declare(strict_types=1);
namespace Drupal\mymodule\StackMiddleware;
use Symfony\Component\HttpFoundation\InputBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
final class TrimMiddleware implements HttpKernelInterface {
public function __construct(
private readonly HttpKernelInterface $app
) {
}
public function handle(
Request $request,
int $type = self::MAIN_REQUEST,
bool $catch = TRUE
): Response {
$this->trimBag($request->query);
$this->trimBag($request->request);
return $this->app->handle($request);
}
private function trimBag(InputBag $bag): void {
$bag->replace($this->trimArray($bag->all()));
}
private function trimArray(array $array): array {
return array_map(
function ($value) {
if (is_array($value)) {
return $this->trimArray($value);
}
return is_string($value) ? trim($value) : $value;
},
$array
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment