PHPackages                             ufo-tech/dto-transformer - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. ufo-tech/dto-transformer

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

ufo-tech/dto-transformer
========================

The library provides tools for two-way transformation of DTO objects ⇄ arrays, respecting typing, contracts, and flexible transformation logic.

2.1.0(3w ago)12.1kMITPHPPHP &gt;=8.3

Since Sep 22Pushed 3w ago1 watchersCompare

[ Source](https://github.com/UFO-Tech/dto-transformer)[ Packagist](https://packagist.org/packages/ufo-tech/dto-transformer)[ Docs](https://docs.ufo-tech.space/bin/view/docs/DTOTransformer/?language=en)[ RSS](/packages/ufo-tech-dto-transformer/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (5)Versions (4)Used By (0)

🧩 **ufo/dto-transformer**
-------------------------

[](#-ufodto-transformer)

A PHP library that provides tools for **bidirectional transformation between DTO objects ⇄ arrays**, with full type safety, contracts, and flexible conversion logic. Ideal for JSON-RPC, REST APIs, CLI tools, and any context where data is passed as arrays.

---

📦 Core Components:
------------------

[](#-core-components)

### 🔁 `DTOTransformer`

[](#-dtotransformer)

Central service for:

- transforming arrays into DTOs via `fromArray(...)`;
- serializing DTOs to arrays via `toArray(...)`.

### ⚙️ `IDTOFromArrayTransformer` + `IDTOToArrayTransformer`

[](#️-idtofromarraytransformer--idtotoarraytransformer)

Interfaces for custom transformers that encapsulate specific logic for unpacking/packing particular DTOs.

### 🧱 `BaseDTOFromArrayTransformer`

[](#-basedtofromarraytransformer)

Base class with a default `fromArray()` implementation that includes:

- support check via `supportsClass(...)`;
- key renaming and data normalization;
- constructor argument resolution and instantiation.

### 🚨 `NotSupportDTOException`

[](#-notsupportdtoexception)

Thrown when a transformer does not support the provided DTO class.

---

🧬 Contracts &amp; Traits:
-------------------------

[](#-contracts--traits)

### `IArrayConstructible` + `ArrayConstructibleTrait`

[](#iarrayconstructible--arrayconstructibletrait)

For DTO classes that support construction from arrays:

- Maps constructor arguments automatically;
- Works via `ReflectionParameter`.

### `IArrayConvertible` + `ArrayConvertibleTrait`

[](#iarrayconvertible--arrayconvertibletrait)

For DTO classes that can be serialized to arrays:

- Automatically serializes public and readonly properties;
- Supports field aliasing and `#[DTOAttributesEnum::Hidden]`.

---

🔌 Usage Example:
----------------

[](#-usage-example)

```
use Ufo\DTO\Attributes\AttrDTO;

class UserDto implements IArrayConstructible, IArrayConvertible
{
    use ArrayConstructibleTrait;
    use ArrayConvertibleTrait;

    public readonly $randomNumber;

    public function __construct(
        public string $name,
        public string $email,
    )
    {
        $this->randomNumber = rand(1, 100);
    }
}

class MemberWithFriendsDTO implements IArrayConstructible, IArrayConvertible
{
    use ArrayConstructibleTrait;
    use ArrayConvertibleTrait;

    public function __construct(
        public User $user
        #[AttrDTO(User::class, context: [
            AttrDTO::C_COLLECTION => true,
            AttrDTO::C_RENAME_KEYS => ['randomNumber' => null]
        ])]
        public array $friends
    ) {}
}

$data = [
    'user' => [
        'name' => 'Alex',
        'email' => 'alex@site.com',
        'randomNumber' => 99,
    ],
    'friends' => [
        [
            'name' => 'Ivan',
            'email' => 'ivan@site.com',
            'randomNumber' => 23,
        ],
        [
            'name' => 'Peter',
            'email' => 'peter@site.com',
            'randomNumber' => 14,
        ]
    ]
];

$dto = DTOTransformer::fromArray(MemberWithFriendsDTO::class, $data);
var_dump($dto);
//object(MemberWithFriendsDTO)#...
//  public $user =>
//    object(User)#...
//      public $name => "Alex"
//      public $email => "alex@site.com"
//      public $randomNumber => 12
//
//  public $friends =>
//    array(2) {
//      [0] =>
//        object(User)#...
//          public $name => "Ivan"
//          public $email => "ivan@site.com"
//          public $randomNumber => 23
//      [1] =>
//        object(User)#...
//          public $name => "Peter"
//          public $email => "peter@site.com"
//          public $randomNumber => 11
//    }

$data = DTOTransformer::toArray($dto);
//[
//    'user' => [
//        'name' => 'Alex',
//        'email' => 'alex@site.com',
//        'randomNumber' => 12,
//    ],
//    'friends' => [
//        [
//            'name' => 'Ivan',
//            'email' => 'ivan@site.com',
//            'randomNumber' => 23,
//        ],
//        [
//            'name' => 'Peter',
//            'email' => 'peter@site.com',
//            'randomNumber' => 11,
//        ]
//    ]
//];
```

📖 DocBlock Support
==================

[](#-docblock-support)

The library supports reading DocBlock annotations for constructors and public DTO properties.
This makes it possible to accurately detect expected types even if they are not explicitly declared in the signature.

```
    use Ufo\DTO\Tests\Fixtures\Enum\IntEnum;

    class DocblockDTO
    {
        /**
         * @var array
         */
        public array $formatedCollection = [];

        /**
         * @param array $collection
         */
        public function __construct(
            public string $name,
            public array $collection
        ) {}
    }
```

🔍 How it works

- @var and @param annotations are parsed automatically.
- The library detects union types (UserDto|DummyDTO|IntEnum) and builds the correct collection.
- Supported types:
    - DTO classes (e.g., UserDto, DummyDTO)
    - Enums (e.g., IntEnum)
    - Mixed-type arrays

🚀 Example

When calling DocblockDTO::fromArray($data), the library will automatically:

1. Convert array elements into the correct DTO or enum.
2. Ensure type safety according to the DocBlock.
3. Build a fully initialized object with collections of the required types.

---

🔧 Custom Transformer Example
----------------------------

[](#-custom-transformer-example)

This is a sample **custom transformer** implementing `IDTOFromArrayTransformer` for transforming an `OrderDTO` where `amount` must be cast to float and `createdAt` to `DateTimeImmutable`.

```
use Ufo\RpcObject\DTO\IDTOFromArrayTransformer;
use Ufo\RpcObject\DTO\DTOTransformer;

class OrderDTO
{
    public function __construct(
        public int $id,
        public float $amount,
        public DateTimeImmutable $createdAt,
    ) {}
}

final class OrderTransformer implements IDTOFromArrayTransformer
{
    public static function fromArray(
        string $classFQCN,
        array $data,
        array $renameKey = []
    ): object {
        $data['amount'] = (float) $data['amount'];
        $data['createdAt'] = new DateTimeImmutable($data['createdAt']);

        return DTOTransformer::fromArray($classFQCN, $data, $renameKey);
    }

    public static function supportsClass(string $classFQCN): bool
    {
        return is_a($classFQCN, OrderDTO::class, true);
    }
}
```

---

### 🧩 With attribute-based transformer:

[](#-with-attribute-based-transformer)

```
use Ufo\DTO\Attributes\AttrDTO;

class MemberWithOrdersDTO implements IArrayConstructible, IArrayConvertible
{
    use ArrayConstructibleTrait;
    use ArrayConvertibleTrait;

    public function __construct(
        public User $user,
        #[AttrDTO(Order::class, context: [
            AttrDTO::C_COLLECTION => true,
            AttrDTO::C_TRANSFORMER => OrderTransformer::class
        ])]
        public array $orders
    ) {}
}

$data = [
    'user' => [
        'name' => 'Alex',
        'email' => 'alex@site.com',
    ],
    "orders" => [
        [
            'id' => 101,
            'amount' => '199.90',
            'createdAt' => '2025-05-09T20:00:00+03:00'
        ],
        [
            'id' => 102,
            'amount' => '99.90',
            'createdAt' => '2025-05-08T12:20:00+03:00'
        ]
    ]
];

$dto = DTOTransformer::fromArray(MemberWithOrdersDTO::class, $data);
```

This transformer:

- strictly follows `IDTOFromArrayTransformer`;
- encapsulates complex conversion logic;
- delegates array-to-object conversion to the core transformer.

---

🧠 Library Advantages
--------------------

[](#-library-advantages)

- Full support for PHP 8.3 type system;
- Flexible logic via pluggable custom transformers;
- Type-safe, self-descriptive, and composable architecture;
- Simple attribute-based field control without code duplication;
- Standardized DTO handling for SOA and microservices environments.

###  Health Score

47

—

FairBetter than 94% of packages

Maintenance95

Actively maintained with recent releases

Popularity20

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 64.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~79 days

Total

3

Last Release

22d ago

Major Versions

1.4.0 → 2.0.62026-02-23

### Community

Maintainers

![](https://www.gravatar.com/avatar/82f99012b9213a4af9b94e187ce7806d56c425868ebd442344ebfa5856fada0e?d=identicon)[Valchik](/maintainers/Valchik)

![](https://www.gravatar.com/avatar/87aea0bcf81c64ced7c3a14a1746d603ec6e8acfba62ef85746df40e8c376e7f?d=identicon)[Alex Maistrenko](/maintainers/Alex%20Maistrenko)

---

Top Contributors

[![Ashterix](https://avatars.githubusercontent.com/u/5172394?v=4)](https://github.com/Ashterix "Ashterix (34 commits)")[![valiknik225](https://avatars.githubusercontent.com/u/137418080?v=4)](https://github.com/valiknik225 "valiknik225 (19 commits)")

---

Tags

phpjsonsymfonyarrayrpcValue Objectserializerhydratordata-transfer-objecttransformerdtodeserializerUfo

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ufo-tech-dto-transformer/health.svg)

```
[![Health](https://phpackages.com/badges/ufo-tech-dto-transformer/health.svg)](https://phpackages.com/packages/ufo-tech-dto-transformer)
```

###  Alternatives

[cuyz/valinor

Dependency free PHP library that helps to map any input into a strongly-typed structure.

1.5k8.1M85](/packages/cuyz-valinor)[zakirullin/mess

Convenient array-related routine &amp; better type casting

21228.3k2](/packages/zakirullin-mess)[hi-folks/data-block

Data class for managing nested arrays and JSON data.

1471.9k](/packages/hi-folks-data-block)[selective/transformer

A strictly typed array transformer with dot-access, fluent interface and filters.

3817.2k](/packages/selective-transformer)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
