Skip to content

Commit 13eb0ec

Browse files
committed
added Arrays::toObject()
1 parent af31ced commit 13eb0ec

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/Utils/Arrays.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,4 +280,18 @@ public static function map(array $arr, callable $callback): array
280280
}
281281
return $res;
282282
}
283+
284+
285+
/**
286+
* Converts array to object
287+
* @param object $obj
288+
* @return object
289+
*/
290+
public static function toObject(array $arr, $obj)
291+
{
292+
foreach ($arr as $k => $v) {
293+
$obj->$k = $v;
294+
}
295+
return $obj;
296+
}
283297
}

tests/Utils/Arrays.toObject.phpt

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
/**
4+
* Test: Nette\Utils\Arrays::toObject()
5+
*/
6+
7+
declare(strict_types=1);
8+
9+
use Nette\Utils\Arrays;
10+
use Tester\Assert;
11+
12+
13+
require __DIR__ . '/../bootstrap.php';
14+
15+
16+
test(function () {
17+
$obj = new stdClass;
18+
$res = Arrays::toObject([], $obj);
19+
Assert::same($res, $obj);
20+
Assert::type(stdClass::class, $res);
21+
Assert::same([], (array) $res);
22+
});
23+
24+
test(function () {
25+
$obj = new stdClass;
26+
$res = Arrays::toObject(['a' => 1, 'b' => 2], $obj);
27+
Assert::same($res, $obj);
28+
Assert::type(stdClass::class, $res);
29+
Assert::same(['a' => 1, 'b' => 2], (array) $res);
30+
});

0 commit comments

Comments
 (0)