antwerpes/data-transfer-object

Simple json encoding and decoding for PHP data objects

1.0.5 2024-10-10 11:46 UTC

This package is auto-updated.

Last update: 2024-11-10 12:03:52 UTC


README

Latest Version on Packagist GitHub Code Style Action Status Total Downloads

Simple library for encoding and decoding JSON structures into PHP objects, e.g. to work with API responses in a strongly typed way.

Installation

You can install the package via composer:

composer require antwerpes/data-transfer-object

Usage

Define a class that extends Antwerpes\DataTransferObject\DataTransferObject and define the structure of the object:

use Antwerpes\DataTransferObject\Attributes\Cast;
use Antwerpes\DataTransferObject\Attributes\Map;
use Antwerpes\DataTransferObject\Casts\ArrayCaster;
use Antwerpes\DataTransferObject\DataTransferObject;

class User extends DataTransferObject
{
    public function __construct(
        public string $name;
        #[Cast(CustomDateCaster::class)]
        public DateTimeInterface $birthday;
        #[Map(from: 'address.city')]
        public string $city;
        #[Cast(ArrayCaster::class, itemType: Interest:class)]
        public array $interests;
    ) {}
}

Then you can use the class to decode JSON strings into PHP objects:

$json = '{
    "name": "John Doe",
    "birthday": "1990-01-01",
    "address": {
        "city": "New York"
    },
    "interests": [
        {
            "name": "Music"
        },
        {
            "name": "Programming"
        }
    ]
}';
$user = User::decode(json_decode($json, true));
$encoded = $user->encode();

Custom Casters

You can define custom casters by implementing the Antwerpes\DataTransferObject\CastsProperty interface:

use Antwerpes\DataTransferObject\CastsProperty;

class CustomDateCaster implements CastsProperty
{
    public function unserialize(mixed $value): DateTimeInterface
    {
        return new DateTime($value);
    }
    
    public function serialize(mixed $value): string
    {
        return $value->format('Y-m-d');
    }
}

Mapping

You can map nested properties to a flat structure using the Map attribute:

use Antwerpes\DataTransferObject\Attributes\Map;

class User extends DataTransferObject
{
    #[Map(from: 'address.city', to: 'address.city')]
    public string $city;
}

Validation

Validation is out of scope for this package, use JSON schemas or other libraries like symfony/validator to validate the object.

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Contributions are welcome! Leave an issue on GitHub, or create a Pull Request.

Credits

License

The MIT License (MIT). Please see License File for more information.