优雅的Web / sanitizer
PHP和Laravel框架的清洗库。
v2.2.0
2024-03-24 11:14 UTC
Requires
- php: ^8.0
- illuminate/support: ^6.0|^7.0|^8.0|^9.0|^10.0|^11.0
- illuminate/validation: ^6.0|^7.0|^8.0|^9.0|^10.0|^11.0
- nesbot/carbon: ^1.0|^2.0|^3.0
Requires (Dev)
- phpunit/phpunit: ^9.0|^10.5
README
PHP和Laravel框架的清洗库。
安装
composer require elegantweb/sanitizer
使用方法
use Elegant\Sanitizer\Sanitizer; use Elegant\Sanitizer\Filters\Enum; $data = [ 'title' => ' ', 'name' => ' sina ', 'birth_date' => '06/25/1980', 'email' => '[email protected]', 'json' => '{"name":"value"}', 'enum' => 'H', ]; $filters = [ 'title' => 'trim|empty_string_to_null', 'name' => 'trim|empty_string_to_null|capitalize', 'birth_date' => 'trim|empty_string_to_null|format_date:"m/d/Y","F j, Y"', 'email' => ['trim', 'empty_string_to_null', 'lowercase'], 'json' => 'cast:array', 'enum' => ['trim', new Enum(BackedEnum::class)], ]; $sanitizer = new Sanitizer($data, $filters); var_dump($sanitizer->sanitize());
结果将是
[ 'title' => null, 'name' => 'Sina', 'birth_date' => 'June 25, 1980', 'email' => '[email protected]', 'json' => ['name' => 'value'], 'enum' => BackedEnum::Hearts, ];
Laravel
在Laravel中,您可以通过外观使用Sanitizer
$newData = \Sanitizer::make($data, $filters)->sanitize();
您还可以通过使用SanitizesInput特质并在返回输入时添加返回您想要应用过滤器的filters
方法,来在您的FormRequests中清洗输入。
namespace App\Http\Requests; use Elegant\Sanitizer\Laravel\SanitizesInput; class MyAwesomeRequest extends Request { use SanitizesInput; public function filters() { return [ 'name' => 'trim|capitalize', ]; } }
可选
如果您计划为所有HTTP请求使用清洗器,您可以可选地禁用Laravel的TrimStrings
和ConvertEmptyStringsToNull
中间件。
protected $middleware = [ [...] // \App\Http\Middleware\TrimStrings::class, // \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, [...] ];
然后,您可以使用trim
和empty_string_to_null
过滤器代替
$filters = [ 'some_string_parameter' => 'trim|empty_string_to_null', ];
可用的过滤器
以下过滤器是开箱即用的
自定义过滤器
您可以使用闭包或实现Elegant\Sanitizer\Contracts\Filter
接口的类的名称。
class RemoveStringsFilter implements \Elegant\Sanitizer\Contracts\Filter { public function apply($value, array $options = []) { return str_replace($options, '', $value); } } $filters = [ 'remove_strings' => RemoveStringsFilter::class, 'password' => fn ($value, array $options = []) => sha1($value), ]; $sanitize = new Sanitizer($data, $filters);
Laravel
您可以通过调用类似ServiceProvider的extend方法轻松扩展Sanitizer库,添加自己的自定义过滤器,就像在Laravel中扩展Validator库一样
\Sanitizer::extend($filterName, $closureOrClassName);