PHPackages                             cerbero/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. cerbero/transformer

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

cerbero/transformer
===================

Transform, manipulate, cast and map objects and arrays.

2.4.0(5y ago)135433MITPHPPHP ^7.1||^8.0

Since Feb 27Pushed 5y ago1 watchersCompare

[ Source](https://github.com/cerbero90/Transformer)[ Packagist](https://packagist.org/packages/cerbero/transformer)[ Docs](https://github.com/cerbero90/Transformer)[ RSS](/packages/cerbero-transformer/feed)WikiDiscussions develop Synced 1mo ago

READMEChangelogDependencies (3)Versions (14)Used By (0)

Transformer
===========

[](#transformer)

[![Author](https://camo.githubusercontent.com/fffbc89ca2742dccf8be167716e04b7125a913abae0da6a488131999dab8ca25/68747470733a2f2f696d672e736869656c64732e696f2f7374617469632f76313f6c6162656c3d617574686f72266d6573736167653d6365726265726f393026636f6c6f723d353041424631266c6f676f3d74776974746572267374796c653d666c61742d737175617265)](https://twitter.com/cerbero90)[![PHP Version](https://camo.githubusercontent.com/e62417859cc9fd023d3997f57ed1b6e14cc4f3c9682094c5cd9d9c9b092b7d4c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6365726265726f2f7472616e73666f726d65723f636f6c6f723d253233344635423933266c6f676f3d706870267374796c653d666c61742d737175617265)](https://www.php.net)[![Build Status](https://camo.githubusercontent.com/0309162f5caeaf7d0da1631664edfe0a1598d0345d0fa5c41a2188273c570a53/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f6365726265726f39302f7472616e73666f726d65722f6275696c643f7374796c653d666c61742d737175617265266c6f676f3d676974687562)](https://github.com/cerbero90/transformer/actions?query=workflow%3Abuild)[![Coverage Status](https://camo.githubusercontent.com/ed57cd5e05ee0f45d06b6e1f94f8bd64fbb8831a315bf7645570ae4e2c851fa1/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f636f7665726167652f672f6365726265726f39302f7472616e73666f726d65722e7376673f7374796c653d666c61742d737175617265266c6f676f3d7363727574696e697a6572)](https://scrutinizer-ci.com/g/cerbero90/transformer/code-structure)[![Quality Score](https://camo.githubusercontent.com/9d52bb5c3b134582b9b51ea0af84b91b778204b8396dbe8276dfed6f26f8fafb/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f6365726265726f39302f7472616e73666f726d65722e7376673f7374796c653d666c61742d737175617265266c6f676f3d7363727574696e697a6572)](https://scrutinizer-ci.com/g/cerbero90/transformer)[![Latest Version](https://camo.githubusercontent.com/9b65cdb03bcb8446b733b361f760f19eabe111f3d4499fe17f69a41a93df4c1d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6365726265726f2f7472616e73666f726d65722e7376673f6c6162656c3d76657273696f6e267374796c653d666c61742d737175617265)](https://packagist.org/packages/cerbero/transformer)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![PSR-12](https://camo.githubusercontent.com/9ba5754b3504e97a10e2b2f84770a218e69e544e9de8943eceb0b67599c83c6c/68747470733a2f2f696d672e736869656c64732e696f2f7374617469632f76313f6c6162656c3d636f6d706c69616e6365266d6573736167653d5053522d313226636f6c6f723d626c7565267374796c653d666c61742d737175617265)](https://www.php-fig.org/psr/psr-12/)[![Total Downloads](https://camo.githubusercontent.com/ad03c269762fb61f4241716a6e73a8c56f32c7c4ba99ed479183d8d2b5783c71/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6365726265726f2f7472616e73666f726d65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/cerbero/transformer)

[![SensioLabsInsight](https://camo.githubusercontent.com/c5380a54466d72e9c8ee9c0c995284f40b90da7d13a73870fda724ebbb146b2f/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f35393332656362662d616666332d343863382d396366392d3736333935333061383466352f6269672e706e67)](https://insight.sensiolabs.com/projects/5932ecbf-aff3-48c8-9cf9-7639530a84f5)

Framework agnostic package to transform arrays, objects, arrays of arrays or arrays of objects by manipulating, casting and mapping their properties and keys.

Install
-------

[](#install)

Via Composer

```
$ composer require cerbero/transformer
```

Usage
-----

[](#usage)

Transformers can be created by extending the `AbstractTransformer` class:

```
use Cerbero\Transformer\AbstractTransformer;

class MyTransformer extends AbstractTransformer
{
    protected function getStructure()
    {
        // the array structure you want to obtain
    }
}
```

The method `getStructure()` lets you define how you want the data to be transformed. For example, imagine that this array:

```
[
    'some' => [
        'nested' => [
            'key' => 'hello',
        ],
    ],
    'color'           => 'blue',
    'adminPermission' => '1',
    'status'          => 'pending',
    'date'            => '2015-01-01T00:00:00+00:00',
    'number'          => '22',
    'cents'           => '$0.0500',
    'unneeded'        => true,
    'json'            => '{"foo":"bar"}',
]
```

has to be transformed into:

```
[
    'key' => 'hello',
    'favorites' => [
        'color'  => 'blue',
        'number' => 22,
    ],
    'is_admin'  => true,
    'status'    => 2,
    'important' => [
        'date'  => '2015-01-01',
    ],
    'cents'     => 0.05,
    'json'      => ['foo' => 'bar'],
]
```

All you need to do is implement `getStructure()` as follows:

```
protected function getStructure()
{
  return [
    'key' => 'some.nested.key',
    'favorites' => [
        'color'  => 'color',
        'number' => 'number int',
    ],
    'is_admin'       => 'adminPermission bool',
    'status'         => 'status enum:denied=0,accepted=1,pending=2',
    'important.date' => 'date date:Y-m-d',
    'cents'          => 'cents substr:1|float',
    // The `unneeded` key is not defined, so it will be ignored
    'json'           => 'json arr',
  ];
}
```

In the example above:

- keys are exactly the keys and nested keys that you expect as a result
- values are the old keys and can optionally contain some transformations
- transformations are separated from old keys by space and follow the syntax: `transformation1:param1,param2|transformation2`
- nested keys are defined by using dot notation, e.g.: `some.nested.key`.
- keys that are not present in the array are automatically ignored.

After defining the new structure, you can transform arrays, objects, arrays of arrays or arrays of objects by calling the `transform()` method:

```
$transformer = new MyTransformer($data);
$transformed = $transformer->transform();

// or by using the static factory method:
$transformed = MyTransformer::from($data)->transform();
```

or if you prefer to transform data into a specific object, you may call the method `transformInto()`:

```
$transformer = new MyTransformer($data);
$transformed = $transformer->transformInto(new DataTransferObject);

// or by using the static factory method:
$transformed = MyTransformer::from($data)->transformInto(new DataTransferObject);
```

### Normalize many sources

[](#normalize-many-sources)

Sometimes you may need to normalize data from different sources. In this case only source keys might change, whilst expected keys and transformations remain the same. To avoid repeating code for every source, you may extend the abstract transformer as you normally would but without specifying the source keys:

```
use Cerbero\Transformer\AbstractTransformer;

abstract class MyTransformer extends AbstractTransformer
{
    protected function getStructure()
    {
        return [
            'key' => null,
            'favorites' => [
                'color'  => null,
                'number' => 'int',
            ],
            'is_admin'       => 'bool',
            'status'         => 'enum:denied=0,accepted=1,pending=2',
            'important.date' => 'date:Y-m-d',
            'cents'          => 'substr:1|float',
            'json'           => 'arr',
        ];
    }
}
```

The example above defines only expected keys and related transformations, no source keys. If no transformation is needed, `null` can be set as value.

Finally to map expected keys with keys of different sources, you may now extend your new transformer for each source and implement the method `getKeysMap()`:

```
class Source1Transformer extends MyTransformer
{
    protected function getKeysMap()
    {
        return [
            'key' => 'some.nested.key',
            'favorites' => [
                'color'  => 'color',
                'number' => 'number',
            ],
            'is_admin'       => 'adminPermission',
            'status'         => 'status',
            'important.date' => 'date',
            'cents'          => 'cents',
            'json'           => 'json',
        ];
    }
}
```

Transformations
---------------

[](#transformations)

Any function or class method can be used as a transformation, for example `trim`, `substr:2`, `Class::staticMethod`, `Namespace\Class::instanceMethod` are all valid transformations. Please note that the value to transform is passed as first parameter of the invoked function or method.

Furthermore this package comes with some builtin transformations:

TransformationDescriptionSyntaxarrDecode a JSON or wrap the value into an array`arr`boolCast the value to a boolean`bool`dateTransform the value into a DateTime object or format a date`date` `date:Y-m-d` `date:Y-m-d,UTC` `date:Y-m-d,UTC,UTC`defaultFallback to a default value if the value is `null` or not found`default:foo`enumEnumerate the value with defined associations`enum:denied=0,approved=1,pending=2`floatCast the value to a float and optionally truncate decimals`float` `float:2`intCast the value to an integer`int`objectDecode a JSON or convert the value to an object`object`stringEncode a JSON or convert the value to a string`string`### Custom transformations

[](#custom-transformations)

When functions, methods and builtin transformations are not enough, you may implement your own transformations by adding methods to your transformer, for example:

```
protected function prefix($prefix)
{
    return $prefix . $this->value;
}
```

`prefix` is now a custom transformation that receives a prefix as parameter and prepend it to the value to transform. It can now be applied by using the syntax `prefix:foo` so that the `$prefix` parameter equals `'foo'`. The above example only needs a parameter but you may pass as many arguments as you wish following the syntax `prefix:foo,bar,baz`.

Please note that `$this->value` holds the value obtained from the last transformation applied, so when you pipe more transformations the value is updated by every transformation it passes through.

Another handy property you may use in a custom transformation is `$this->item`, which holds the array or object that contains `$this->value`. It might be useful for example when a custom transformation requires another value from the original item to transform the current value.

Sometimes you may need the same custom transformation in different transformers. You might consider to extract such logic into a class so that it can be easily called from any transformer by using an alias, just like the builtin transformations:

```
use Cerbero\Transformer\Transformations\AbstractTransformation;

class PrefixTransformation extends AbstractTransformation
{
    public function apply(array $parameters)
    {
        return $parameters[0] . $this->value;
    }
}
```

The custom transformation above extends the `AbstractTransformation` class and the parameters are passed in the `apply()` method as an array. Since `PrefixTransformation` follows the convention `Name + Transformation`, it can now be used with the alias `prefix` as we did before e.g.: `prefix:foo`.

Both the properties `$this->value` and `$this->item` are available in the transformation class, just like when you define custom transformations in your transformer.

Most likely your transformation classes are going to have their own namespace, it can be defined by implementing the method `getCustomTransformationNamespace()` in your transformer:

```
protected function getCustomTransformationNamespace(): string
{
    return 'My\Namespace';
}
```

Change log
----------

[](#change-log)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Testing
-------

[](#testing)

```
$ composer test
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CODE\_OF\_CONDUCT](CODE_OF_CONDUCT.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Andrea Marco Sartori](https://twitter.com/cerbero90)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity21

Limited adoption so far

Community21

Small or concentrated contributor base

Maturity75

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~195 days

Recently: every ~149 days

Total

12

Last Release

1951d ago

Major Versions

0.1.1 → 1.0.02018-06-02

1.0.0 → 2.0.02019-05-26

PHP version history (4 changes)0.0.0PHP &gt;=5.3.0

0.0.2PHP &gt;=5.4.0

2.0.0PHP ^7.0

2.4.0PHP ^7.1||^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/596523?v=4)[Matteo Picciolini](/maintainers/cerbero)[@cerbero](https://github.com/cerbero)

---

Top Contributors

[![cerbero90](https://avatars.githubusercontent.com/u/5838106?v=4)](https://github.com/cerbero90 "cerbero90 (34 commits)")[![philsturgeon](https://avatars.githubusercontent.com/u/67381?v=4)](https://github.com/philsturgeon "philsturgeon (9 commits)")[![RobLoach](https://avatars.githubusercontent.com/u/25086?v=4)](https://github.com/RobLoach "RobLoach (4 commits)")[![marcqualie](https://avatars.githubusercontent.com/u/101022?v=4)](https://github.com/marcqualie "marcqualie (4 commits)")[![reinink](https://avatars.githubusercontent.com/u/882133?v=4)](https://github.com/reinink "reinink (3 commits)")[![frankdejonge](https://avatars.githubusercontent.com/u/534693?v=4)](https://github.com/frankdejonge "frankdejonge (3 commits)")[![assertchris](https://avatars.githubusercontent.com/u/200609?v=4)](https://github.com/assertchris "assertchris (2 commits)")[![kdubuc](https://avatars.githubusercontent.com/u/895661?v=4)](https://github.com/kdubuc "kdubuc (2 commits)")[![marcrobertscamao](https://avatars.githubusercontent.com/u/249061?v=4)](https://github.com/marcrobertscamao "marcrobertscamao (2 commits)")[![browner12](https://avatars.githubusercontent.com/u/5232313?v=4)](https://github.com/browner12 "browner12 (2 commits)")[![bcrowe](https://avatars.githubusercontent.com/u/752603?v=4)](https://github.com/bcrowe "bcrowe (2 commits)")[![zackkitzmiller](https://avatars.githubusercontent.com/u/111536?v=4)](https://github.com/zackkitzmiller "zackkitzmiller (1 commits)")[![barryvdh](https://avatars.githubusercontent.com/u/973269?v=4)](https://github.com/barryvdh "barryvdh (1 commits)")[![bencorlett](https://avatars.githubusercontent.com/u/181919?v=4)](https://github.com/bencorlett "bencorlett (1 commits)")[![BreiteSeite](https://avatars.githubusercontent.com/u/2171105?v=4)](https://github.com/BreiteSeite "BreiteSeite (1 commits)")[![clarkeash](https://avatars.githubusercontent.com/u/1612186?v=4)](https://github.com/clarkeash "clarkeash (1 commits)")[![dstockto](https://avatars.githubusercontent.com/u/775393?v=4)](https://github.com/dstockto "dstockto (1 commits)")[![hassankhan](https://avatars.githubusercontent.com/u/1781985?v=4)](https://github.com/hassankhan "hassankhan (1 commits)")[![nyamsprod](https://avatars.githubusercontent.com/u/51073?v=4)](https://github.com/nyamsprod "nyamsprod (1 commits)")[![pborreli](https://avatars.githubusercontent.com/u/77759?v=4)](https://github.com/pborreli "pborreli (1 commits)")

---

Tags

castingmanipulatormapperphptransformerarrayobjectmaptransformtransformercastmanipulate

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/cerbero-transformer/health.svg)

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

###  Alternatives

[symfony/property-access

Provides functions to read and write from/to an object or array using a simple string notation

2.8k295.3M2.5k](/packages/symfony-property-access)[webpatser/laravel-uuid

Laravel integration for webpatser/uuid - High-performance drop-in UUID replacements (15% faster than Ramsey). Provides Str macros, HasUuids trait, facades, and casts. RFC 4122/9562 compliant.

1.8k17.3M129](/packages/webpatser-laravel-uuid)[cuyz/valinor

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

1.5k9.2M108](/packages/cuyz-valinor)[aimeos/map

Easy and elegant handling of PHP arrays as array-like collection objects similar to jQuery and Laravel Collections

4.2k412.9k11](/packages/aimeos-map)[yzen.dev/plain-to-class

Class-transformer to transform your dataset into a structured object

16293.9k6](/packages/yzendev-plain-to-class)[zakirullin/mess

Convenient array-related routine &amp; better type casting

21228.9k2](/packages/zakirullin-mess)

PHPackages © 2026

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