• Reading time ~ 1 min
  • 04.12.2022

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.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297