verborum/sanitizer

Simple sanitizer library

This package's canonical repository appears to be gone and the package has been frozen as a result.

1.0.2 2023-05-20 11:13 UTC

This package is not auto-updated.

Last update: 2024-06-02 13:12:42 UTC


README

Please don't upload to GitHub

Library for sanitizing JSON or array with needed data types.

Installation

  • Add the package:
    composer require verborum/sanitizer
    
  • Run the Composer command to install the dependenciy:
    composer install
    

Usage example

$fieldTypeMap = [  
	'a' => SanitizerField::new(IntegerType::class),  
	'b' => [  
		// If necessary, you can write your own data types using DataProcessorInterface 
		// for data processing and DataTypeInterface to explain to the SanitizerField 
		// how to work with what
		SanitizerField::new(FloatType::class),  
		SanitizerField::new(StringType::class),  
		SanitizerField::new(RussianMobilePhoneType::class),  
	],  
];

// Data for sanitizing. It can be an array already or a JSON string.
$dataJson  = '{"a":"23","b":["-0.25","81231231212","+7 (123) 123-12-12"]}';\
$dataArray = [  
	'a' => '23',  
	'b' => [  
		'-0.25',  
		'81231231212',  
		'+7 (123) 123-12-12'  
	],  
];

// Actually they are equal in this case.
$sanitizedJson  = Sanitizer::sanitize($fieldTypeMap, $dataJson);
$sanitizedArray = Sanitizer::sanitize($fieldTypeMap, $dataArray);

// Both sanitized data are equal to this
// [  
//      'a' => 23,  
//      'b' => [  
// 		     -0.25,  
// 		     '81231231212',  
// 		     '71231231212'  
// 	 ],  
// ]
// Also it is available to describe array of one data type with any length.
$fieldTypeMap = [  
    SanitizerField::new(FloatType::class, isArray: true),  
];

$dataJson  = '{"0", "1.25", "-3,14"}';\
$dataArray = [  
	'0',
	'1.25',
	'-3.14'
];

$sanitizedJson  = Sanitizer::sanitize($fieldTypeMap, $dataJson);
$sanitizedArray = Sanitizer::sanitize($fieldTypeMap, $dataArray);

// [
//       0,
//       1.25,
//       -3.14,
// ]
// If any errors here you can get all of them.
$fieldTypeMap = [
    'a' => SanitizerField::new(IntegerType::class),
    'b' => SanitizerField::new(StringType::class),
    'c' => SanitizerField::new(FloatType::class),
];

// Wrong 'a' and 'c' data types.
$data = '{"a":"asd","b":"qwe","c":"zxc"}';

try {
    Sanitizer::sanitize($fieldTypeMap, $data);
} catch (SanitizerException $e) {
    $errors = $e->getErrors();
}
// $errors is an array with all invalid keys and types.
// $errors = [
//     'a' => SanitizerField::new(IntegerType::class),
//     'c' => SanitizerField::new(FloatType::class),
// ]