Skip to content

Instantly share code, notes, and snippets.

@sirawitpra
Last active April 24, 2017 08:01
Show Gist options
  • Save sirawitpra/90c7da95aec72d2d01b3be1e0a00edfa to your computer and use it in GitHub Desktop.
Save sirawitpra/90c7da95aec72d2d01b3be1e0a00edfa to your computer and use it in GitHub Desktop.
Laravel 5.4 awesome middleware
<?php
namespace Illuminate\Foundation\Http\Middleware;
class ConvertEmptyStringsToNull extends TransformsRequest
{
/**
* Transform the given value.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function transform($key, $value)
{
return is_string($value) && $value === '' ? null : $value;
}
}
<?php
namespace Illuminate\Foundation\Http\Middleware;
use Closure;
use Symfony\Component\HttpFoundation\ParameterBag;
class TransformsRequest
{
/**
* The additional attributes passed to the middleware.
*
* @var array
*/
protected $attributes = [];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, ...$attributes)
{
$this->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);
if ($request->isJson()) {
$this->cleanParameterBag($request->json());
} else {
$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
* @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;
}
}
<?php
namespace Illuminate\Foundation\Http\Middleware;
class TrimStrings extends TransformsRequest
{
/**
* The attributes that should not be trimmed.
*
* @var array
*/
protected $except = [
//
];
/**
* Transform the given value.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function transform($key, $value)
{
if (in_array($key, $this->except, true)) {
return $value;
}
return is_string($value) ? trim($value) : $value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment