Last active
September 22, 2020 16:38
-
-
Save thexpand/fc1cf6a0dea5df772178576758577456 to your computer and use it in GitHub Desktop.
A PSR-15 middleware class to normalize query parameters (e.g. to turn a "true" or a "false" string from a query parameter to a boolean true or false for the next middlewares/handlers in the pipeline.
This file contains hidden or 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 Application\Middleware; | |
use Psr\Http\Message\ResponseInterface; | |
use Psr\Http\Message\ServerRequestInterface; | |
use Psr\Http\Server\MiddlewareInterface; | |
use Psr\Http\Server\RequestHandlerInterface; | |
class NormalizeQueryParamsMiddleware implements MiddlewareInterface | |
{ | |
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface | |
{ | |
return $handler->handle( | |
$request->withQueryParams( | |
$this->normalize( | |
$request->getQueryParams() | |
) | |
) | |
); | |
} | |
private function normalize($value) | |
{ | |
if ($value === 'true') { | |
return true; | |
} | |
if ($value === 'false') { | |
return false; | |
} | |
if (is_array($value)) { | |
$newValue = []; | |
foreach ($value as $childKey => $childValue) { | |
$newValue[$childKey] = $this->normalize($childValue); | |
} | |
return $newValue; | |
} | |
return $value; | |
} | |
} |
@rieschl I think installing laminas-filter
when I just need to convert string 'true'
and string 'false'
to bool true
and bool false
respectively is an overkill. I would argue against normalizing string '0'
and string '1'
, as there could be another parameter that we want to be a string of zero or a string of one, e.g. consider an implementation that uses the query for filtering results and you have a minimum and maximum values. But I would rather extend the current gist to support numeric values by casting them to integers or floats respectively.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice idea, but why don't you just use the Laminas filter?
Edit: Or at least, I'd add normalization for
'0'
and'1'
, too.