t-kuni / php-normalizer
Boilerplate package for creating other packages.
Installs: 257
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 2
Forks: 0
Open Issues: 3
Type:project
Requires
- php: >=7.1
- league/container: ^3.3
Requires (Dev)
- phpunit/phpunit: 8.*
This package is auto-updated.
Last update: 2024-10-29 05:41:07 UTC
README
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, // ], // ] // ]
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, // ]
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', // ], // ] // ]