Skip to content

Instantly share code, notes, and snippets.

@logue
Created May 22, 2018 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save logue/fdb8f995269cae314b822256d81ff4b7 to your computer and use it in GitHub Desktop.
Save logue/fdb8f995269cae314b822256d81ff4b7 to your computer and use it in GitHub Desktop.
全角を含む空白文字をトリムして改行コードをLFにし、空白しか残らなかったらNULLを入れるLaravel用Middleware
<?php
/**
* 入力文字列のサニタイズ.
*
* @author Logue <logue@hotmail.co.jp>
* @copyright 2018 Logue All Rights Reserved
* @license MIT
*/
namespace App\Http\Middleware;
use Closure;
class Sanitize
{
/**
* 全角を含む空白文字を削除し、LF改行に統一。空白だった場合NULLにする。
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
$input = $request->all();
$trimmed = [];
foreach ($input as $key => $val) {
// 最初に文字列の前後の空白をpreg_replaceで削除する。
// 次に改行コードをLFに統一する。
// 最後にtrimで前後の改行文字を削除する。
$processed = trim(
str_replace([chr(0x0d).chr(0x0a), chr(0x0d), chr(0x0a)], "\n",
preg_replace('/\A[\p{C}\p{Z}]++|[\p{C}\p{Z}]++\z/u', '', $val)
)
);
// 空白が残った場合NULLを代入する。
$trimmed[$key] = empty($processed) ? null : $processed;
}
$request->merge($trimmed);
return $next($request);
}
}
@logue
Copy link
Author

logue commented May 22, 2018

入力変数を見境なくトリムするのでバイナリデーターを扱うときは注意。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment