Skip to content

Commit

Permalink
Map Hydrate
Browse files Browse the repository at this point in the history
  • Loading branch information
bajb committed Feb 21, 2020
1 parent 2a5de5b commit 08d01ed
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 3 deletions.
26 changes: 23 additions & 3 deletions src/Objects.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,7 @@ public static function pnonempty($object, array $properties, $default = null)
*
* @throws \Exception
*/
public static function hydrate(
$destination, $source, array $properties = null, $copyNull = true
)
public static function hydrate($destination, $source, array $properties = null, $copyNull = true)
{
if(!is_object($destination) || !is_object($source))
{
Expand All @@ -110,6 +108,28 @@ public static function hydrate(
}
}

public static function mapHydrate($destination, $source, array $properties, $copyNull = true)
{
if(!is_object($destination) || !is_object($source))
{
throw new \Exception("mapHydrate() must be given objects");
}

foreach($properties as $property => $callback)
{
$newVal = static::property($source, $property);
if(is_callable($callback))
{
$newVal = $callback($newVal);
}

if($newVal !== null || $copyNull)
{
$destination->$property = $newVal;
}
}
}

/**
* Return an array with only the public properties
*
Expand Down
44 changes: 44 additions & 0 deletions tests/ObjectsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,50 @@ public function testHydrate()
Objects::hydrate(['' => ''], $source, []);
}

public function testMapHydrate()
{
$dest = new stdClass();
$dest->nullify = 'Please';

$source = new PropertyClass();
$source->name = 'Test';
$source->age = 19;
$source->nullify = null;

Objects::mapHydrate($dest, $source, [null]);
$this->assertEquals('Please', $dest->nullify);

Objects::mapHydrate($dest, $source, ['nullify' => true], false);
$this->assertEquals('Please', $dest->nullify);

Objects::mapHydrate($dest, $source, ['nullify' => true], true);
$this->assertNull($dest->nullify);

Objects::mapHydrate($dest, $source, ['name' => true]);

$this->assertObjectHasAttribute('name', $dest);
$this->assertEquals('Test', $dest->name);

$this->assertObjectNotHasAttribute('age', $dest);
Objects::mapHydrate($dest, $source, ['age' => true]);

$this->assertObjectHasAttribute('age', $dest);
$this->assertEquals('19', $dest->age);

$dest->name = null;
Objects::mapHydrate($dest, $source, ['name' => true]);
$this->assertObjectHasAttribute('name', $dest);
$this->assertEquals('Test', $dest->name);

Objects::mapHydrate($dest, $source, ['age' => function ($val) { return $val * 10; }]);

$this->assertObjectHasAttribute('age', $dest);
$this->assertEquals(190, $dest->age);

$this->setExpectedException("Exception");
Objects::mapHydrate(['' => ''], $source, []);
}

public function testClassShortName()
{
$expectations = [
Expand Down

0 comments on commit 08d01ed

Please sign in to comment.