优雅的Web/sanitizer

PHP和Laravel框架的清洗库。

v2.2.0 2024-03-24 11:14 UTC

This package is auto-updated.

Last update: 2024-08-28 04:16:23 UTC


README

GitHub release (latest by date) GitHub Workflow Status

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的TrimStringsConvertEmptyStringsToNull中间件。

protected $middleware = [
    [...]
    // \App\Http\Middleware\TrimStrings::class,
    // \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    [...]
];

然后,您可以使用trimempty_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);

灵感