PHP code example of clazz / typed-sanitizer
1. Go to this page and download the library: Download clazz/typed-sanitizer library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
clazz / typed-sanitizer example snippets
use Clazz\Typed\Types\Type;
// 假设有个接口想要一个用户的数据,而外部输入是这样:
$input = [
'id' => '123',
'name' => ' James William ',
'age' => '12',
'isMale' => '1',
];
// 可以定义我们想要的是这样的:
$userDefinition = Type::arr([
'id' => 'int',
'name' => Type::string()->trim()->length('< 30'),
'age' => Type::int()->isRequired(),
'isMale' => Type::boolean(),
]);
// 然后就可以执行净化了:
$sanitizedUserData = $userDefinition->sanitize($input);
// 看看得到的数据,果然是预期的:
var_export($sanitizedUserData);
//输出:
// array (
// 'id' => 123,
// 'name' => 'James William',
// 'age' => 12,
// 'isMale' => true,
// )
use Clazz\Typed\Types\Type;
use Clazz\Typed\Sanitizer;
// 假设有个接口想要一个用户的数据,而外部输入是这样:
$input = [
'id' => '123',
'name' => ' James William ',
'age' => '12',
'isMale' => '1',
];
// 类型定义 + 执行净化了:
$sanitizedUserData = Sanitizer::getSanitized([
'id' => 'int',
'name' => Type::string()->trim()->length('< 30'),
'age' => Type::int()->isRequired(),
'isMale' => Type::boolean(),
], $input);
use Clazz\Typed\Types\Type;
use Clazz\Typed\Illuminate\Support\Facades\Input;
// 假设有个接口想要一个用户的数据,而HTTP的输入参数是这样:
// id=123&name=%20%20James%20William%20%20&age=12&isMale=1
// 类型定义 + 执行净化了:
$sanitizedUserData = Input::getSanitized([
'id' => 'int',
'name' => Type::string()->trim()->length('< 30'),
'age' => Type::int()->isRequired(),
'isMale' => Type::boolean(),
]);