Skip to content

Commit

Permalink
added Arrays::toObject()
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Mar 15, 2019
1 parent af31ced commit 13eb0ec
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Utils/Arrays.php
Original file line number Diff line number Diff line change
Expand Up @@ -280,4 +280,18 @@ public static function map(array $arr, callable $callback): array
}
return $res;
}


/**
* Converts array to object
* @param object $obj
* @return object
*/
public static function toObject(array $arr, $obj)
{
foreach ($arr as $k => $v) {
$obj->$k = $v;
}
return $obj;
}
}
30 changes: 30 additions & 0 deletions tests/Utils/Arrays.toObject.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

/**
* Test: Nette\Utils\Arrays::toObject()
*/

declare(strict_types=1);

use Nette\Utils\Arrays;
use Tester\Assert;


require __DIR__ . '/../bootstrap.php';


test(function () {
$obj = new stdClass;
$res = Arrays::toObject([], $obj);
Assert::same($res, $obj);
Assert::type(stdClass::class, $res);
Assert::same([], (array) $res);
});

test(function () {
$obj = new stdClass;
$res = Arrays::toObject(['a' => 1, 'b' => 2], $obj);
Assert::same($res, $obj);
Assert::type(stdClass::class, $res);
Assert::same(['a' => 1, 'b' => 2], (array) $res);
});

0 comments on commit 13eb0ec

Please sign in to comment.