, (*1)
Often when receiving data from a client in an API or from a form request, you'll find yourself running the same data
cleaning operations such as transforming 'false'
to the boolean false
, converting ''
to null
etc. This can be a pain., (*2)
This package simplifies the process drastically., (*3)
Installation
- Install the package with composer :
composer require acid-solutions/input-sanitizer
Laravel users
- Laravel 5.5+ uses Package Auto-Discovery, so doesn't require you to manually add the ServiceProvider and the Facade alias.
If you don't use auto-discovery or if you use a Laravel 5.4- version, add the package service provider in the
register()
method from your app/Providers/AppServiceProvider.php
:
// input sanitizer
// https://github.com/ACID-Solutions/input-sanitizer
$this->app->register(AcidSolutions\InputSanitizer\Laravel\InputSanitizerServiceProvider::class);
- Then, add the package facade alias in the
$aliases
array from the config/app.php
config file.
'aliases' => [
'...',
'InputSanitizer' => AcidSolutions\InputSanitizer\Laravel\Facades\InputSanitizer::class
]
When this provider is booted, you'll gain access to a InputSanitizer
facade, which you may use in your controllers., (*4)
public function index()
{
$inputs = $request->all();
$sanitizedInputs = \InputSanitizer::sanitize($inputs);
}
Without Laravel
InputSanitizer ships with native implementations of the bootloader and facade. In order to use it import class., (*5)
// import the package facade
use Acid\InputSanitizer\Native\Facades\InputSanitizer;
// sanitize your entries
$input = ['false', '3', ''];
$sanitizedInput = InputSanitizer::sanitize($input);
// produces [false, 3, null]
Usage
The only public method in the package is sanitize($input, $default = null, $jsonDecodeAssoc = false)
, (*6)
Call the sanitizer as following:, (*7)
$data = ['null', 'true'];
$sanitized = InputSanitizer::sanitize($data);
$input
can be a string, boolean, number, array, object or JSON string, (*8)
Examples of the cleaned data:, (*9)
'' => null
'null' => null
'false' => false
'true' => true
'on' => true
'3' => 3
'5.07' => 5.07
When using arrays and objects, the method will sanitize each element in the given input and return an array (or object)
with the cleaned values., (*10)
$default
can be used to return a default value if the resulting cleaned input is null
or false
, (*11)
Example:, (*12)
InputSanitizer::sanitize('', 'hello');
// will return 'hello'
$jsonDecodeAssoc
is used for decoding JSON.
See php json_decode documentation, (*13)
$jsonDecodeAssoc = true // default is false
$input = json_decode($input, null, $jsonDecodeAssoc);
// will decode your json as associative array (and as object if false)
Credits