PHP code example of t-kuni / php-normalizer
1. Go to this page and download the library: Download t-kuni/php-normalizer 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/ */
t-kuni / php-normalizer example snippets
$input = ' hoge fuga ';
$filters = ['trim', 'empty_to_null'];
$result = Normalizer::normalize($input, $filters);
// $result is...
// 'hoge fuga'
$n = new Normalizer([
'name' => ['trim', 'empty_to_null'],
'age' => ['trim', 'empty_to_null', 'integer'],
'gender' => ['trim', 'empty_to_null', 'integer'],
]);
$result = $n->normalize([
'name' => ' hoge fuga ',
'age' => ' 20 ',
]);
// $result is...
// [
// 'name' => 'hoge fuga',
// 'age' => 20,
// 'gender' => null,
// ]
$n = new Normalizer([
'users.*.name' => ['trim', 'empty_to_null'],
'users.*.age' => ['trim', 'empty_to_null', 'integer'],
]);
$result = $n->normalize([
'users' => [
[
'name' => ' hoge fuga ',
'age' => ' 20 ',
],
[
'name' => '',
'age' => ' 20 ',
],
]
);
// $result is...
// [
// 'users' => [
// [
// 'name' => 'hoge fuga',
// 'age' => 20,
// ],
// [
// 'name' => null,
// 'age' => 20,
// ],
// ]
// ]
use ...\Condition as Cond;
Cond::is(0)->to(1);
Cond::is(null)->to(1);
Cond::isEmpty()->to(null);
Cond::toInt();
Cond::isNotNull()->toInt();
Cond::isEmpty()->to(new CustomFilter());
$n = new Normalizer([
'name' => ['trim', Cond::isEmpty()->toNull()],
'age' => ['trim', Cond::isEmpty()->toNull(), Cond::isNotEmpty()->toInt()],
'gender' => ['trim', Cond::isEmpty()->toNull(), Cond::isNotEmpty()->toInt()],
]);
$result = $n->normalize([
'name' => ' hoge fuga ',
'age' => ' 20 ',
]);
// $result is...
// [
// 'name' => 'hoge fuga',
// 'age' => 20,
// 'gender' => null,
// ]
$customFilter = new class implements FilterContract
{
public function apply($input)
{
return $input . '-suffix';
}
}
Container::container()->get(FilterProviderContract::class)
->addFilter('custom_filter_name', $customFilter);
$n = new Normalizer([
'users.*.name' => ['trim', 'custom_filter_name'],
]);
$result = $n->normalize([
'users' => [
[
'name' => 'john',
],
[
'name' => 'eric',
],
]
]);
// $result is...
// [
// 'users' => [
// [
// 'name' => 'john-suffix',
// ],
// [
// 'name' => 'eric-suffix',
// ],
// ]
// ]