酸溶液/输入消毒剂

此软件包已被废弃,不再维护。未建议替代软件包。

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

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附带bootloader和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)

鸣谢