kalheim/sanitizer

PHP 数据清洗器,内置 Laravel 支持。

v1.0.1 2016-03-25 01:48 UTC

This package is not auto-updated.

Last update: 2024-09-28 19:41:43 UTC


README

Build Status StyleCI Code Coverage Scrutinizer Code Quality Latest Stable Version Latest Unstable Version License

PHP 数据清洗器,内置 Laravel 支持。

安装

composer require kalfheim/sanitizer

用法

use Alfheim\Sanitizer\Sanitizer;

// Create a new sanitizer instance by passing an array of rules to the `Sanitizer::make` method...
$sanitizer = Sanitizer::make([
    'email' => 'trim',
]);

// Simulate some user input...
$input = [
    'email' => 'name@example.com ', // Notice the space.
];

// Now we will sanitize some data by passing an array to the `sanitize` method...
var_dump($sanitizer->sanitize($input)); // ['email' => 'name@example.com']

// It is also possible to pass the data by reference using the `sanitizeByRef` method...
$sanitizer->sanitizeByRef($input);
var_dump($input); // ['email' => 'name@example.com']

示例

// Wildcard example...

$input = [
    'name'  => 'Ola nordmann',
    'email' => 'Name@example.com ',
];

$sanitizer = Sanitizer::make([
    '*'     => 'trim',          // `*` is a wildcard which will apply to all fields.
    'name'  => 'ucwords',       // Uppercase first char of each word in the name field.
    'email' => 'mb_strtolower', // Lowercase each letter in the email field.
]);

var_dump($sanitizer->sanitize($input));
// ['name' => 'Ola Nordmann', 'email' => 'name@example.com']
// Multiple rules and arguments...

$sanitizer = Sanitizer::make([
    'name'  => 'trim|ucwords', // Trim, then uppercase first char of each word.
    'email' => 'preg_replace:/\+\w+/::{{ VALUE }}',
]);

// The `email` rule might be a handful, but it is really quite simple. 
// The rule translates to `$sanitizedValue = preg_replace('/\+\w+/', '', $value)`.
// It will sanitize an email like `name+foo@example.com` to `name@example.com`.

// The `{{ VALUE }}` string is a magic constant that the sanitizer will replace
// with the value currently being sanitized.

// By default, the value will be implicitly bound to the first argument in the list,
// however, you can place it where ever you need to satisfy the function being called.

$sanitizer = Sanitizer::make([
    'foo' => 'mb_substr:0:1',
    'bar' => 'mb_substr:{{ VALUE }}:0:1',
]);

// In the example above, both rules will achieve the same end result.

注册者

注册者允许您将自定义清洗函数绑定到清洗器。

use Alfheim\Sanitizer\Sanitizer;
use Alfheim\Sanitizer\Registrar\BaseRegistrar;

// Create a new registrar instance...
$registrar = new BaseRegistrar;

// Add custom sanitation rules to the registrar...
$registrar->register('palindromify', function (string $value) {
    return sprintf('%s%s', $value, strrev($value));
});

// Create a new sanitizer and bind the registrar...
$sanitizer = Sanitizer::make([
    'number' => 'palindromify',
])->setRegistrar($registrar);


$input = $sanitizer->sanitize([
    'number' => '123',
]);

var_dump($input); // ['number' => '123321']

Laravel 支持

按照常规方法在您的 config/app.php 中注册服务提供者...

Alfheim\Sanitizer\SanitizerServiceProvider::class,

扩展 FormRequest

这是该包发光的地方。 通过在您的基类 App\Http\Requests\Request 上扩展 Alfheim\Sanitizer\Laravel\FormRequest(而不是默认的 Illuminate\Foundation\Http\FormRequest),您将能够在给定的表单请求上的 sanitize 方法中定义清洗规则,类似于您在 rules 方法中定义验证规则。

让我用代码展示...

// app/Http/Requests/Request.php

namespace App\Http\Requests;

use Alfheim\Sanitizer\Laravel\FormRequest;
// Instead of `Illuminate\Foundation\Http\FormRequest`

abstract class Request extends FormRequest
{
    //
}

就是这样!现在在表单请求上定义清洗规则变得非常简单...

// app/Http/Requests/FooRequest.php

namespace App\Http\Requests;

class FooRequest extends Request
{
    // Sanitation rules...
    public function sanitize()
    {
        return [
            'name'  => 'trim|ucwords',
            'email' => 'trim|mb_strtolower',
        ];
    }

    // And of course, validation is defined as per usual...
    public function rules()
    {
        return [
            'name'  => 'required',
            'email' => 'required|email',
        ];
    }
}

为了完整性,我将展示控制器...

namespace App\Http\Controllers;

use App\Http\Requests\FooRequest;

class FooController extends Controller
{
    public function create(FooRequest $request)
    {
        // At this point, the $request will be both sanitized and validated.
        // You may go ahead and access the input as usual:

        $request->all();
        $request->input('name');
        $request->only(['name', 'email']);
        // etc...
    }
}

辅助特性

Alfheim\Sanitizer\Laravel\SanitizesRequests

这个特性在类上添加了一个 sanitize 方法。如果您想在控制器中清洗用户输入而不设置自定义请求类,这可能很有用(然而,它可以从任何地方使用。)

public function sanitize(Illuminate\Http\Request $request, array $ruleset): array

示例用法...

namespace App\Http\Controllers\FooController;

use Illuminate\Http\Request;
use Alfheim\Sanitizer\Laravel\SanitizesRequests;

class FooController extends Controller
{
    use SanitizesRequests;

    public function store(Request $request)
    {
        $input = $this->sanitize($request, [
            'name'  => 'trim|ucwords',
            'email' => 'trim|mb_strtolower',
        ]);

        // $input now contains the sanitized request input.
    }
}

通过 Laravel 注册自定义清洗函数

服务提供者将在 IoC 容器中注册一个共享的 Alfheim\Sanitizer\Registrar\RegsitrarInterface 实例,然后将其设置在后续的 Alfheim\Sanitizer\Sanitizer 实例上。这意味着您可以轻松地注册自定义清洗函数...

use Alfheim\Sanitizer\Registrar\RegistrarInterface;

// Standalone...
app(RegistrarInterface::class)->register('yell', $callable);

// In a method resolved by the container, perhaps a service provider...
public function registerSanitizers(RegistrarInterface $registrar)
{
    $registrar->register('yell', function (string $value) {
        return mb_strtoupper($value);
    });
}

// You may also resolve an object from the IoC container using `class@method` notation...
app(RegistrarInterface::class)->register('foo', 'some.service@sanitizerMethod');

许可证

MIT © Kristoffer Alfheim