• Stars
    star
    14
  • Rank 1,438,076 (Top 29 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 9 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

Transformer

Author PHP Version Build Status Coverage Status Quality Score Latest Version Software License PSR-12 Total Downloads

SensioLabsInsight

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

Install

Via Composer

$ composer require cerbero/transformer

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

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

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:

Transformation Description Syntax
arr Decode a JSON or wrap the value into an array arr
bool Cast the value to a boolean bool
date Transform 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
default Fallback to a default value if the value is null or not found default:foo
enum Enumerate the value with defined associations enum:denied=0,approved=1,pending=2
float Cast the value to a float and optionally truncate decimals float float:2
int Cast the value to an integer int
object Decode a JSON or convert the value to an object object
string Encode a JSON or convert the value to a string string

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

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

Testing

$ composer test

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Security

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

Credits

License

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

More Repositories

1

json-parser

🧩 Zero-dependencies lazy parser to read JSON of any dimension and from any source in a memory-efficient way.
PHP
676
star
2

lazy-json

🐼 Framework-agnostic package to load JSON of any dimension and from any source into Laravel lazy collections recursively.
PHP
235
star
3

enum

🎲 Zero-dependencies PHP library to supercharge enum functionalities.
PHP
188
star
4

command-validator

Validate Laravel console commands input.
PHP
160
star
5

laravel-enum

Discontinued. Enum generator for Laravel.
PHP
136
star
6

eloquent-inspector

πŸ•΅οΈ Inspect Laravel Eloquent models to collect properties, relationships and more.
PHP
115
star
7

Workflow

Laravel 5 package to create extendible and maintainable apps by harnessing the power of pipelines.
PHP
109
star
8

query-filters

Laravel package to filter Eloquent model records based on query parameters. Fully inspired by the Laracasts episode https://laracasts.com/series/eloquent-techniques/episodes/4
PHP
84
star
9

lazy-json-pages

πŸ“œ Framework-agnostic package to load items from any paginated JSON API into a Laravel lazy collection via async HTTP requests.
PHP
82
star
10

notifiable-exception

Laravel package to send notifications when some exceptions are thrown.
PHP
76
star
11

exception-handler

Extend the Laravel exception handler to let service providers determine how custom exceptions should be handled.
PHP
60
star
12

laravel-dto

Data Transfer Object (DTO) for Laravel
PHP
55
star
13

Auth

Laravel authentication module.
PHP
49
star
14

octane-testbench

β›½ Set of utilities to test Laravel applications powered by Octane.
PHP
42
star
15

sql-dumper

Laravel package to dump SQL queries, related EXPLAIN and location in code in different formats.
PHP
23
star
16

pest-plugin-laravel-octane

β›½ Pest plugin to test Laravel applications powered by Octane.
PHP
21
star
17

json-objects

Extract objects from large JSON files, endpoints or streams while saving memory.
PHP
20
star
18

dto

Data Transfer Object (DTO).
PHP
16
star
19

Sublime-Text-PHP-and-Laravel-Snippets

Sublime Text snippets to ease development with PHP and Laravel.
13
star
20

console-tasker

🦾 Laravel package to create lean, powerful, idempotent and beautiful Artisan commands.
PHP
10
star
21

workflow-demo

Demo for Workflow repository
CSS
9
star
22

Date

Framework agnostic and easy to use tool to work with dates.
PHP
6
star
23

start

Mac service written in Automator to run several softwares and commands by pressing a hot key.
AppleScript
2
star
24

fluent-api

Framework agnostic starting point to perform fluent calls to any API.
PHP
1
star
25

Affiliate

PHP
1
star