PHP Classes

File: doc/4_using_transformers.md

Recommend this page to a friend!
  Classes of Julian Finkler   JSON Object Mapper   doc/4_using_transformers.md   Download  
File: doc/4_using_transformers.md
Role: Documentation
Content type: text/markdown
Description: Documentation
Class: JSON Object Mapper
Create objects of classes mapped from JSON strings
Author: By
Last change:
Date: 5 years ago
Size: 1,295 bytes
 

Contents

Class file image Download

Using Transformers

? Go to index

Often it's required to transform the data before mapping, during the mapping or after the mapping. E.q. a special time format needs to be converted to an DateTime object.

{
    "german_date_time": "27.04.2018, 22:05:47 Uhr"
}

For this case, you can create a class which implements the TransformerInterface:

class GermanDateTimeTransformer implements MintWare\JOM\TransformerInterface
{
    // Converts "27.04.2018, 22:05:47 Uhr" to a DateTime object
    public static function transform($data)
    {
        list($date, $time) = explode(', ', substr($data, 0, -4));
        return new DateTime($date . ' ' . $time);
    }

    // Converts a DateTime object to "27.04.2018, 22:05:47 Uhr"
    public static function reverseTransform($data)
    {
        $formatted = null;
        if ($data != null) {
            $formatted = $data->format('d.m.Y, H:i:s') . ' Uhr';
        }

        return $formatted;
    }
}

In the object you can refer the transformer by its FQCN:

class SomeObject
{
    / @JsonField(name="german_date_time", type="string", postTransformer="\GermanDateTimeTransformer") */
    public $dateTime;
}

Available arguments are preTransformer, transformer and postTransformer