t-kuni/php-normalizer

Boilerplate package for creating other packages.

v0.0.1 2019-08-08 03:22 UTC

This package is auto-updated.

Last update: 2024-10-29 05:41:07 UTC


README

Scrutinizer Code Quality Code Coverage Build Status Code Intelligence Status

PHP Normalizer

In development...

Features

Single Normalize

$input   = '   hoge  fuga ';
$filters = ['trim', 'empty_to_null'];

$result = Normalizer::normalize($input, $filters);

// $result is...
// 'hoge  fuga'

Multiple Normalize

Flat Array

$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,
// ]

Nested Array

$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,
//     ],
//   ]
// ]

More details

Advanced Filtering

You can use Filter facade when you want to specify arguments.

Filter::replace('aaa', 'bbb')

Conditional Filtering

(TBD)

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,
// ]

More details

Add Custom Filter

$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',
//         ],
//     ]
// ]