-
-
Save thelebster/39acbb63a0744260f9700a40921dbdbd to your computer and use it in GitHub Desktop.
TrimMiddleware for Drupal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services: | |
http_middleware.trim: | |
class: Drupal\mymodule\StackMiddleware\TrimMiddleware | |
arguments: ['@kernel'] | |
tags: | |
- { name: http_middleware } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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