Transformer is a PHP package for sanitizing and formatting data powered by Laravel’s validation components. The package uses a familiar Laravel validation-like syntax to transform data using callable functions, classes, and more:
use Closure;
// example available functions at runtime:
function to_carbon($value)
{
return new Carbon\Carbon($value);
}
function only_numbers($value)
{
return preg_replace("/[^0-9]/",'',$value);
}
$input = [
'first_name' => ' jim ',
'last_name' => ' thompson',
'phone_number' => '123-456-7890',
'date_of_birth' => "1991-05-01",
];
(new DataTransformer($input, [
'first_name' => 'trim|ucfirst',
'last_name' => 'trim|ucfirst',
'phone_number' => 'only_numbers',
'date_of_birth' => 'to_carbon|->format:m/d/y',
]))->transform();
// Returns:
// [
// "first_name" => "Jim",
// "last_name" => "Thompson",
// "phone_number" => "1234567890",
// "date_of_birth" => "05/01/91",
// ]
Those familiar with Laravel’s validation API will notice the string-based transformer rules. Also, as seen in the snippet, this package has a “chainable” syntax (to_carbon|->format:m/d/y
) that can chain additional calls on a piece of data.
You can also transform data using closures or a class implementing the provided Transformable
interface. Additionally, this package supports nested array data using dot notation, wildcard inputs (apply functions on keys matching a wildcard pattern), and more.
You can learn more about this package, get full installation instructions, and view the source code on GitHub.