treehouselabs/entity-merger

This package is abandoned and no longer maintained. No replacement package was suggested.
There is no license information available for the latest version (2.0.2) of this package.

An entity merger

2.0.2 2015-07-22 07:57 UTC

This package is not auto-updated.

Last update: 2020-01-24 14:47:43 UTC


README

Entity Merger is a library that can merge two entities.

Build Status Scrutinizer Code Quality Code Coverage

Usage

Define as a service:

tree_house.entity_merger:
    class: TreeHouse\EntityMerger\EntityMerger
    arguments:
      - @jms_serializer
      - @doctrine
      - @jms_serializer.metadata_factory

Then use it as followed:

$merger = $container->get('tree_house.entity_merger');

$original = new Entity();
$original->setTitle('A');

var_dump($original->getAuthor()); // output: NULL

$update = new Entity();
$update->setTitle('B');
$update->setAuthor('TreeHouse');

$original = $merger->merge($original, $update);

var_dump($original->getTitle()) // output: "B"
var_dump($original->getAuthor()); // output: "TreeHouse"

To update null values, you can hint the merger to do this:

$merger = $container->get('tree_house.entity_merger');

$original = new Entity();
$original->setTitle('A');

$update = new Entity();
$update->setTitle(null);
$update->setAuthor('TreeHouse');

$original = $merger->merge($original, $update, null, true);

var_dump($original->getTitle()) // output: NULL
var_dump($original->getAuthor()); // output: "TreeHouse"

It is also possible to exclude fields by giving an array with property names which must be included:

$merger = $container->get('tree_house.entity_merger');

$original = new Entity();
$original->setTitle('A');

$update = new Entity();
$update->setTitle('B');
$update->setAuthor('TreeHouse');

// include the given fields, make sure to camelcase the fieldnames when needed
$exclusionStrategy = new \TreeHouse\EntityMerger\Serializer\Exclusion\FieldsExclusionStrategy([
    'title'
]);

$original = $merger->merge($original, $update, $exclusionStrategy);

var_dump($original->getTitle()) // output: "B"
var_dump($original->getAuthor()); // output: NULL

It is also possible to pass an array with fields and values:

$merger = $container->get('tree_house.entity_merger');

$original = new Entity();
$original->setTitle('A');
$original->setAuthor('TreeHouse');

$update = ['title' => 'new title'];

$original = $merger->merge($original, $update);

var_dump($original->getTitle()); // output: "new title"
var_dump($original->getAuthor()); // output: "TreeHouse"