31.7 C
Pakistan
Thursday, June 13, 2024

Use the Transformer Package’s validation, logging, caching, interception, and security features to clean up and format data in PHP.

Transformer is a PHP package that uses Laravel’s validation components to format and sanitize data. The package transforms data using callable functions, classes, and other features using a syntax that is similar to Laravel validation:

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 who are acquainted with Laravel’s validation API will observe that the transformer rules are string-based. This package also has a “chainable” syntax (to_carbon|->format:m/d/y) that allows for the chaining of additional calls on a given piece of data, as demonstrated in the snippet.

Additionally, you can use a class that implements the given Transformable interface or closures to transform data. This package also supports wildcard inputs (apply functions on keys matching a wildcard pattern), nested array data using dot notation, and more.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles