酸溶液/输入消毒剂

此包已废弃且不再维护。未建议替代包。

输入消毒剂,将字符串转换为布尔值、数字等。

1.0.2 2017-11-10 15:26 UTC

This package is not auto-updated.

Last update: 2022-04-30 06:33:14 UTC


README

Source Code Latest Version Build Status Coverage Status Total Downloads License: MIT SensioLabsInsight

通常在从API或表单请求接收客户端数据时,你会发现自己正在运行相同的数据清洗操作,例如将 'false' 转换为布尔值 false,将 '' 转换为 null 等。这可能会很麻烦。

此包极大地简化了此过程。

安装

  • 使用composer安装此包
composer require acid-solutions/input-sanitizer

Laravel用户

  • Laravel 5.5+ 使用包自动发现,因此不需要你手动添加ServiceProvider和Facade别名。如果你不使用自动发现或使用Laravel 5.4-版本,请在你的 app/Providers/AppServiceProvider.php 中的 register() 方法中添加包服务提供者
// input sanitizer
// https://github.com/ACID-Solutions/input-sanitizer
$this->app->register(AcidSolutions\InputSanitizer\Laravel\InputSanitizerServiceProvider::class);
  • 然后,在 config/app.php 配置文件的 $aliases 数组中添加包facade别名。
'aliases' => [
    '...',
    'InputSanitizer' => AcidSolutions\InputSanitizer\Laravel\Facades\InputSanitizer::class
]

当此提供者启动时,你将能够访问一个 InputSanitizer facade,你可以在控制器中使用它。

public function index()
{
    $inputs = $request->all();
    $sanitizedInputs = \InputSanitizer::sanitize($inputs);
}

非Laravel

InputSanitizer自带了启动器和facade的原生实现。为了使用它,请导入类。

// import the package facade
use Acid\InputSanitizer\Native\Facades\InputSanitizer;

// sanitize your entries
$input = ['false', '3', ''];
$sanitizedInput = InputSanitizer::sanitize($input);

// produces [false, 3, null]

用法

包中唯一的公共方法是 sanitize($input, $default = null, $jsonDecodeAssoc = false)

按照以下方式调用消毒剂

$data = ['null', 'true'];
$sanitized = InputSanitizer::sanitize($data);

$input 可以是字符串、布尔值、数字、数组、对象或JSON字符串

清洗数据的示例

''      => null
'null'  => null
'false' => false
'true'  => true
'on'    => true
'3'     => 3
'5.07'  => 5.07

当使用数组和对象时,此方法将清洗给定输入中的每个元素,并返回包含清洗值的数组(或对象)。

可以使用 $default 在清洗后的输入为 nullfalse 时返回默认值

示例

InputSanitizer::sanitize('', 'hello');
// will return 'hello'

$jsonDecodeAssoc 用于解码JSON。
请参阅php json_decode 文档

$jsonDecodeAssoc = true // default is false
$input = json_decode($input, null, $jsonDecodeAssoc);
// will decode your json as associative array (and as object if false)

致谢