Sanitize and Format Data in PHP with the Transformer Package

Packages

October 20th, 2022

Sanitize and Format Data in PHP with the Transformer Package

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:

1use Closure;
2 
3// example available functions at runtime:
4function to_carbon($value)
5{
6 return new Carbon\Carbon($value);
7}
8 
9function only_numbers($value)
10{
11 return preg_replace("/[^0-9]/",'',$value);
12}
13 
14$input = [
15 'first_name' => ' jim ',
16 'last_name' => ' thompson',
17 'phone_number' => '123-456-7890',
18 'date_of_birth' => "1991-05-01",
19];
20 
21(new DataTransformer($input, [
22 'first_name' => 'trim|ucfirst',
23 'last_name' => 'trim|ucfirst',
24 'phone_number' => 'only_numbers',
25 'date_of_birth' => 'to_carbon|->format:m/d/y',
26]))->transform();
27 
28// Returns:
29// [
30// "first_name" => "Jim",
31// "last_name" => "Thompson",
32// "phone_number" => "1234567890",
33// "date_of_birth" => "05/01/91",
34// ]

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.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.