TransformsRequest.php
TLDR
This file, TransformsRequest.php
, is a part of the Illuminate\Foundation\Http\Middleware namespace in the Demo Projects project. It contains a class called TransformsRequest, which is a middleware that handles an incoming request by cleaning its data.
Methods
handle
This method handles an incoming request and cleans its data.
clean
This method cleans the request's data by calling the cleanParameterBag
method for query, JSON, and request parameter bags.
cleanParameterBag
This method cleans the data in the parameter bag by replacing it with the cleaned array of values.
cleanArray
This method cleans the data in a given array by iterating through each element and calling the cleanValue
method for each key-value pair.
cleanValue
This method cleans a given value by checking if it is an array or not. If it is an array, it calls the cleanArray
method recursively. Otherwise, it calls the transform
method.
transform
This method transforms the given value and returns it as is.
<?php
namespace Illuminate\Foundation\Http\Middleware;
use Closure;
use Symfony\Component\HttpFoundation\ParameterBag;
class TransformsRequest
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$this->clean($request);
return $next($request);
}
/**
* Clean the request's data.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function clean($request)
{
$this->cleanParameterBag($request->query);
if ($request->isJson()) {
$this->cleanParameterBag($request->json());
} elseif ($request->request !== $request->query) {
$this->cleanParameterBag($request->request);
}
}
/**
* Clean the data in the parameter bag.
*
* @param \Symfony\Component\HttpFoundation\ParameterBag $bag
* @return void
*/
protected function cleanParameterBag(ParameterBag $bag)
{
$bag->replace($this->cleanArray($bag->all()));
}
/**
* Clean the data in the given array.
*
* @param array $data
* @param string $keyPrefix
* @return array
*/
protected function cleanArray(array $data, $keyPrefix = '')
{
foreach ($data as $key => $value) {
$data[$key] = $this->cleanValue($keyPrefix.$key, $value);
}
return $data;
}
/**
* Clean the given value.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function cleanValue($key, $value)
{
if (is_array($value)) {
return $this->cleanArray($value, $key.'.');
}
return $this->transform($key, $value);
}
/**
* Transform the given value.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function transform($key, $value)
{
return $value;
}
}