The Property Transform library provides a powerful way to automatically transform DTO properties using PHP attributes.
This allows you to apply transformations such as trimming, formatting, and sanitization directly on properties, while also supporting nested object transformation and dependency injection.
- β Transform DTO properties using PHP attributes
- β Supports multiple transformations per property (e.g., trim + lowercase)
- β Applies transformations to nested objects automatically
- β
Supports callable PHP functions (
trim,strtolower, etc.) - β Works with Dependency Injection (DI) for custom transformations
- β
Supports class methods as transformers (
[ClassName::class, 'method']) - β Lightweight & efficient β no runtime overhead
Install via Composer:
composer require mackrais-organization/property-transformYou can use built-in PHP functions as transformers by adding attributes:
use MackRais\PropertyTransform\Transform;
class UserDto
{
#[Transform('trim')]
#[Transform('strtolower')]
public string $name;
#[Transform('intval')]
public string $age;
}Then, apply transformations:
$dto = new UserDto();
$dto->name = ' John Doe ';
$dto->age = '25';
$dataTransformer = new DataTransformer(new TransformerFactory($container));
$dataTransformer->transform($dto);
echo $dto->name; // Output: "john doe"
echo $dto->age; // Output: 25 (converted to integer)If a DTO contains another DTO, transformations will apply recursively:
class AddressDto
{
#[Transform('trim')]
#[Transform('strtolower')]
public string $city;
}
class UserDto
{
#[Transform('trim')]
#[Transform('strtolower')]
public string $name;
#[Transform] // Required for nested transformation
public AddressDto $address;
}Usage:
$address = new AddressDto();
$address->city = ' New York ';
$dto = new UserDto();
$dto->name = ' Jane Doe ';
$dto->address = $address;
$dataTransformer->transform($dto);
echo $dto->name; // Output: "jane doe"
echo $dto->address->city; // Output: "new york"You can also define a custom transformer method inside a class:
class SecuritySanitizer
{
public function sanitize(?string $input): string
{
return strip_tags((string) $input);
}
}And use it as a transformer:
class UserDto
{
#[Transform([SecuritySanitizer::class, 'sanitize'])]
public string $bio;
}Transformers can be registered as public services in Symfony or any DI container.
Example using PSR-11 Container:
use Psr\Container\ContainerInterface;
$container = new SomePsr11Container();
$factory = new TransformerFactory($container);
$dataTransformer = new DataTransformer($factory);Now, any service-based transformer (like SecuritySanitizer) will be automatically resolved.
Property Transform is released under the MIT License. See the LICENSE.md file for details.