/** @test */ public function itReversesPropertiesOnObjects() { $map = new Map(); $map->map('leftA', 'rightA')->map('leftB', 'rightB')->map('leftC', 'rightC'); $from = (object) ['leftA' => null, 'leftB' => null, 'leftC' => null]; $to = (object) ['rightA' => 'value for a', 'rightB' => 'value for b', 'rightC' => 'value for c']; $mapper = new Mapper(); $mapper->reverse($from, $to, $map); $this->assertEquals('value for a', $from->leftA); $this->assertEquals('value for b', $from->leftB); $this->assertEquals('value for c', $from->leftC); }
/** * Reverse the property links of a map. * * @param object|array $from * @param object|array $to * @param MapInterface $map * * @return self */ public function reverse(&$from, $to, MapInterface $map) { $mapper = new Mapper($this->propertyAccess); foreach ($map->getEmbeddedCollections() as $collection) { // New value $value = []; // Source items $source = $this->propertyAccess->getValue($to, $collection->getTo()); foreach ($source as $item) { $newItem = $collection->getFactory()->reverse($item); $value[] = $mapper->reverse($newItem, $item, $collection->getMap()); } $this->propertyAccess->setValue($from, $collection->getFrom(), $value); } return $this; }
/** @test */ public function itReversesEmbeddedCollections() { $from = new Stubs\From(); $to = new Stubs\To('value from mapped foo'); $to->setMappedChildren([new Stubs\From('foo child 0'), new Stubs\From('foo child 1'), new Stubs\From('foo child 2')]); $map = new Map(); $map->map('foo', 'mappedFoo')->embedCollection('children', 'mappedChildren', (new Map())->map('[foo]', 'foo'), new CallbackFactory(function ($value) { return new Stubs\To(); }, function ($value) { return []; })); $mapper = new Mapper(); $mapper->reverse($from, $to, $map); $this->assertEquals('value from mapped foo', $from->getFoo()); $this->assertCount(3, $from->getChildren()); $count = 0; foreach ($from->getChildren() as $child) { $this->assertTrue(is_array($child)); $this->assertEquals(sprintf('foo child %d', $count++), $child['foo']); } }