From f578bbce25843492fc996ac96797e0395e16cf2e Mon Sep 17 00:00:00 2001 From: Taylor Otwell Date: Tue, 17 Jan 2017 15:35:13 -0600 Subject: [PATCH] Ship middleware to trim strings and convert empty strings to null. --- .../Middleware/ConvertEmptyStringsToNull.php | 18 ++++ .../Http/Middleware/TransformsRequest.php | 101 ++++++++++++++++++ .../Http/Middleware/TrimStrings.php | 31 ++++++ 3 files changed, 150 insertions(+) create mode 100644 src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php create mode 100644 src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php create mode 100644 src/Illuminate/Foundation/Http/Middleware/TrimStrings.php diff --git a/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php b/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php new file mode 100644 index 000000000000..813c9cf123ce --- /dev/null +++ b/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php @@ -0,0 +1,18 @@ +attributes = $attributes; + + $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); + + $this->cleanParameterBag($request->request); + + if ($request->isJson()) { + $this->cleanParameterBag($request->json()); + } + } + + /** + * 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 + * @return array + */ + protected function cleanArray(array $data) + { + return collect($data)->map(function ($value, $key) { + return $this->cleanValue($key, $value); + })->all(); + } + + /** + * 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); + } + + return $this->transform($key, $value); + } + + /** + * Transform the given value. + * + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function transform($key, $value) + { + return $value; + } +} diff --git a/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php b/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php new file mode 100644 index 000000000000..a17cb46c9cf5 --- /dev/null +++ b/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php @@ -0,0 +1,31 @@ +except)) { + return $value; + } + + return is_string($value) ? trim($value) : $value; + } +}