Sanitizer es una biblioteca de desinfectantes PHP simple y independiente sin dependencias.
Utiliza el compositor para instalar y actualizar:
composer require "truongwp/sanitizer=*"
El desinfectante requiere PHP> = 5.3
<?php
$ sanitizer = new Truongwp Sanitizer Sanitizer ();
$ input = array (
' name ' => ' Foo bar ' ,
' age ' => ' 24 ' ,
);
$ rules = array (
' name ' => ' trim|strtolower|ucwords ' ,
' age ' => ' intval ' ,
);
$ output = $ sanitizer -> sanitize ( $ input , $ rules ); El $output :
array (
' name ' => ' Foo Bar ' ,
' age ' => 24 ,
); Se pueden pasar múltiples reglas como delimitador de cadena por | o usar una matriz:
<?php
$ rules = array (
' name ' => array ( ' trim ' , ' strtolower ' , ' ucwords ' ),
' age ' => ' intval ' ,
);Por defecto, el nombre de la regla es la función PHP. Por lo tanto, puede agregar fácilmente una función personalizada para desinfectar.
<?php
function trim_slasses ( $ value ) {
return trim ( $ value , ' / ' );
}
$ sanitizer = new Truongwp Sanitizer Sanitizer ();
$ input = array (
' name ' => ' //foo ' ,
);
$ rules = array (
' name ' => ' trim_slasses ' ,
);
$ output = $ sanitizer -> sanitize ( $ input , $ rules );El resultado:
array (
' name ' => ' foo ' ,
) Si desea pasar parámetros adicionales a la función desinfectante, puede agregarlos a regla el nombre y delimitado por : .
<?php
function prefix_suffix ( $ value , $ prefix = '' , $ suffix = '' ) {
return $ prefix . $ value . $ suffix ;
}
$ sanitizer = new Truongwp Sanitizer Sanitizer ();
$ input = array (
' name ' => ' foo ' ,
);
$ rules = array (
' name ' => ' prefix_suffix:prefix_:_suffix ' ,
);
$ output = $ sanitizer -> sanitize ( $ input , $ rules );El resultado:
array (
' name ' => ' prefix_foo_suffix ' ,
)También puede agregar la clase de desinfectante personalizado utilizando SanitizerRegistry.
<?php
class DateFormatSanitizer implements Truongwp Sanitizer Contracts RuleSanitizer
{
/**
* Sanitize value.
*
* @param mixed $value Value need to sanitize.
* @return mixed
*/
public function sanitize ( $ value )
{
$ args = func_get_args ();
$ format = empty ( $ args [ 1 ]) ? ' Y-m-d ' : $ args [ 1 ];
$ timestamp = strtotime ( $ value );
return date ( $ format , $ timestamp );
}
}
// Register rule sanitizers.
Truongwp Sanitizer Registries SanitizerRegistry:: set ( ' date_format ' , new DateFormatSanitizer ());
$ sanitizer = new Truongwp Sanitizer Sanitizer ();
$ input = array (
' day ' => ' 05/30/2017 ' ,
);
$ rules = array (
' name ' => ' date_format:Y-m-d ' ,
);
$ output = $ sanitizer -> sanitize ( $ input , $ rules );El resultado:
array (
' day ' => ' 2017-05-30 ' ,
)Colaborador: @truongwp
Los informes de errores o las solicitudes de extracción son bienvenidos.